pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
        buildDiscarder logRotator(
          artifactDaysToKeepStr: '30',
          artifactNumToKeepStr: '100',
          daysToKeepStr: '365',
          numToKeepStr: '1000'
        )
        timeout(time: 6, unit: 'HOURS')
    }

    parameters {
        choice(name: 'ENVIRONMENT', choices: ['qa', 'prod'], description: 'The environment to run against.')
        string(name: 'SKIP', defaultValue: '0', description: 'How many days back should we start processing?')
        string(name: 'MONTHS', defaultValue: '2', description: 'Number of months to process')
        booleanParam(name: 'RELOAD', defaultValue: false, description: 'when checked is sends to context "reload": "True"')
        booleanParam(name: 'ONLY_UPDATE_JOB', defaultValue: false, description: 'when checked the Jenkins job only updates itself. No execution triggers')
    }

    environment {
        CREDENTIALS_ID = "${params.ENVIRONMENT == 'prod' ? 'prod-feed-ingestion-exec-creds' : 'qa-feed-ingestion-exec-creds'}"
    }

    triggers {
        parameterizedCron(
            '''
               H 23 * * * % ENVIRONMENT=prod; SKIP=1;MONTHS=2
            '''
        )
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                script {
                    def buildUser = env.BUILD_USER_ID ?: 'unknown'
                    currentBuild.displayName = "[${params.ENVIRONMENT}] by ${buildUser}"
                }
                library "jenkins-global-libraries@master"
            }
        }
        stage('Run exec job') {
            when {
                expression {
                    params.ONLY_UPDATE_JOB == false
                }
            }
            steps {
                withEcr {
                    withCredentials([[
                    $class: 'AmazonWebServicesCredentialsBinding',
                    credentialsId: env.CREDENTIALS_ID,
                    accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                    secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
                    ]])
                    {
                        dockerRun(
                            imageTag: 'latest',
                            script: '/var/app/feed_ingestion/flows/spotify_marketshare/exec.py',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: params.ENVIRONMENT,
                                RELOAD: params.RELOAD,
                                MONTHS: params.MONTHS,
                                SKIP: params.SKIP,
                                CHECK_STATUS: true,

                                AWS_ACCESS_KEY_ID: env.AWS_ACCESS_KEY_ID,
                                AWS_SECRET_ACCESS_KEY: env.AWS_SECRET_ACCESS_KEY,
                                AWS_DEFAULT_REGION: 'us-east-1'
                            ]
                        )
                    }
                }
            }
        }
    }
    post {
        failure {
            script {
                if (params.ENVIRONMENT == 'prod') {
                    slackSend (
                        color: "danger",
                        channel: "#data-alerts",
                        message: """The build ${currentBuild.fullDisplayName} has failed.! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"""
                    )
                }
            }
        }
        aborted {
            script {
                if (params.ENVIRONMENT == 'prod') {
                    slackSend (
                        color: "danger",
                        channel: "#data-alerts",
                        message: """The build ${currentBuild.fullDisplayName} has failed.! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"""
                    )
                }
            }
        }
    }
}