pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
        buildDiscarder logRotator(
          artifactDaysToKeepStr: '30',
          artifactNumToKeepStr: '100',
          daysToKeepStr: '365',
          numToKeepStr: '1000'
        )
        timeout(time: 6, unit: 'HOURS')
        datadog(collectLogs: false, tags: ["service:swf-amazon-music", "application_family:data-platform", "licensor:${Env:LICENSOR}", "environment:${Env:ENVIRONMENT}"])
    }

    parameters {
        choice(name: 'ENVIRONMENT', choices: ['qa', 'prod'], description: 'The environment to run against.')
        choice(name: 'LICENSOR', choices: ['ALL', 'theorchard', 'sme', 'awal', 'altafonte'], description: 'Licensor.')
        choice(name: 'REPORT', choices: ['ALL', 'unlimited', 'prime', 'adsupported'], description: 'Report name.')
        string(name: 'SKIP', defaultValue: '1', description: 'Number of periods to skip going backwards.')
        string(name: 'DAYS', defaultValue: '4', description: 'Number of days to exec going backward')
        string(name: 'CONTEXT_DATE', description: 'Single context date.')
        string(name: 'COUNTRIES', description: 'comma-separated list of countries example "AU,US"')
        booleanParam(name: 'BUILD_DBT', defaultValue: false, description: 'When True it triggers build DBT models')
        booleanParam(name: 'CHECK_STATUS', defaultValue: false, description: 'Check status and do not run already completed context.')
        choice(name: 'EXPECTED_STATUS', choices: ['INGESTED', 'DOWNLOADED', 'POPULATED_RAW_TABLE'], description: 'Value of status which considered as completed.')
        string(name: 'MAX_CONCURRENT_FLOWS', defaultValue: '5', description: 'Limit of active SWF flow executions.')
        choice(name: 'CONCURRENCY_STRATEGY', choices: ['WAIT', 'IGNORE', 'SKIP', 'FAIL'], description: 'Action to perform when concurrency limit reached. [SKIP] - do not execute contexts which are above limit. [IGNORE] - execute all contexts ignoring limit. [FAIL] - fail execution if limit is reached. [WAIT] - delay context execution until limit free.')
        choice(name: 'RELOAD', choices: ['False', 'Soft', 'True'], description: '"True" - clear status before start, "Soft" - skip tasks loading raw data, "None" - normal processing')
        string(name: 'CONTEXT', defaultValue: '{}', description: 'Optional context arguments')
        booleanParam(name: 'WAIT_UNTIL_COMPLETE', defaultValue: false, description: 'If "True" then wait until finish execution.')
        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 * * * * % REPORT=ALL;ENVIRONMENT=prod;LICENSOR=ALL;SKIP=1;DAYS=3;CHECK_STATUS=true
            '''
        )
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                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/amazon_music/exec.py',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: params.ENVIRONMENT,
                            
                                COUNTRIES: params.COUNTRIES,
                                BUILD_DBT: params.BUILD_DBT,
                                SKIP: params.SKIP,
                                DAYS: params.DAYS,
                                CHECK_STATUS: params.CHECK_STATUS,
                                EXPECTED_STATUS: params.EXPECTED_STATUS,
                                MAX_CONCURRENT_FLOWS: params.MAX_CONCURRENT_FLOWS,
                                CONCURRENCY_STRATEGY: params.CONCURRENCY_STRATEGY,
                                LICENSOR: params.LICENSOR,
                                REPORT: params.REPORT,
                                CONTEXT_DATE: params.CONTEXT_DATE,
                                RELOAD: params.RELOAD,
                                CONTEXT: params.CONTEXT,
                                WAIT_UNTIL_COMPLETE: params.WAIT_UNTIL_COMPLETE,

                                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>)"""
                    )
                }
            }
        }
    }
}