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: ['prod', 'qa'], description: 'The environment to run against.')
        string(name: 'DAYS_BACK', defaultValue: '1', description: 'ingest charts starting from SKIP days back. "1" means from yesterday')
        string(name: 'PLATFORM_NAMES', defaultValue: 'appleMusic,amazon,linemusic,shazam,spotify,soundcloud,recochoku,tiktok,youtube,deezer')
        string(name: 'CONTEXT_DATE', description: ' "YYYY-MM-DD" - start date for ingestion (not inclusive) ')
        string(name: 'CONTEXT_DATE_LIMIT', description: ' "YYYY-MM-DD" - end date for ingestion (not inclusive)  ')
        booleanParam(name: 'SKIP_UPDATE_RELATIONS', defaultValue: false, description: ' True - to skip Neo4j task in new flow')
        booleanParam(name: 'WAIT_UNTIL_COMPLETE', defaultValue: false)
        booleanParam(name: 'KAFKA', defaultValue: true, description:'use Kafka to update relations in Neo4j' )
        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'}"
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                script {
                    currentBuild.displayName = "${params.ENVIRONMENT} #${currentBuild.number}"
                }
                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: '/bin/bash /var/app/feed_ingestion/flows/chartmetric_charts/exec.sh',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: "'${params.ENVIRONMENT}'",
                                FEED_INGESTION_TABLE: "'${params.ENVIRONMENT}_feed_ingestion_status'",
                                AWS_ACCESS_KEY_ID: "'${AWS_ACCESS_KEY_ID}'",
                                AWS_SECRET_ACCESS_KEY: "'${AWS_SECRET_ACCESS_KEY}'",
                                AWS_DEFAULT_REGION: 'us-east-1',

                                DAYS_BACK: "${params.DAYS_BACK}",
                                PLATFORM_NAMES: "${params.PLATFORM_NAMES}",
                                CONTEXT_DATE_LIMIT: "${params.CONTEXT_DATE_LIMIT}",
                                SKIP_UPDATE_RELATIONS: "${params.SKIP_UPDATE_RELATIONS}",
                                KAFKA: "${params.KAFKA}",
                                CONTEXT_DATE: "${params.CONTEXT_DATE}",
                                WAIT_UNTIL_COMPLETE: params.WAIT_UNTIL_COMPLETE
                            ]
                        )
                    }
                }
            }
        }
    }
    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>)"""
                    )
                }
            }
        }
    }
}