pipeline {
    agent any

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

    parameters {
        choice(name: 'ENVIRONMENT', choices: ['qa', 'prod'], description: 'The environment to run against.')
        choice(name: 'VENDOR_NAME', choices: ['SME', 'POD_SUB_LLC'], description: 'Name of the vendor for which data needs to be ingested')
        choice(name: 'SOURCE', choices: ['Monthly', 'Weekly', 'Daily'], description: "Source or the report's date type.")
        string(name: 'SKIP', defaultValue: '1', description: 'How many days back should we start processing?')
        string(name: 'DAYS', defaultValue: '1', description: 'Number of days to process')
        string(name: 'CONTEXT_DATE', description: 'YYYY-MM-DD. Has precedence over DAYS and SKIP')
        booleanParam(name: 'RELOAD', defaultValue: false, description: 'when checked is sends to context "reload": "True"')
        string(name: 'MAX_FLOWS', defaultValue: '1', description: 'Max concurrent flows to run')
        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 */6 * * * % ENVIRONMENT=prod;  SOURCE=Daily; SKIP=2; DAYS=2; MAX_FLOWS=2; VENDOR_NAME=SME;
            H */6 * * 3 % ENVIRONMENT=prod;  SOURCE=Weekly; SKIP=3; VENDOR_NAME=SME;
            H */6 5 * * % ENVIRONMENT=prod;  SOURCE=Monthly; SKIP=5; VENDOR_NAME=SME;

            H */6 * * * % ENVIRONMENT=prod;  SOURCE=Daily; SKIP=2; DAYS=2; MAX_FLOWS=2; VENDOR_NAME=POD_SUB_LLC;
            H */6 * * 3 % ENVIRONMENT=prod;  SOURCE=Weekly; SKIP=3; VENDOR_NAME=POD_SUB_LLC;
            H */6 5 * * % ENVIRONMENT=prod;  SOURCE=Monthly; SKIP=5; VENDOR_NAME=POD_SUB_LLC;
            '''
        )
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                script {
                    def buildUser = env.BUILD_USER_ID ?: "<unknown>"
                    currentBuild.displayName = "[${params.ENVIRONMENT}] ${params.VENDOR_NAME} 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/apple_podcasts_subscription_snapshot_monthly/exec.py',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: params.ENVIRONMENT,
                                VENDOR_NAME: params.VENDOR_NAME,
                                DAYS: params.DAYS,
                                SKIP: params.SKIP,
                                SOURCE: params.SOURCE,
                                RELOAD: params.RELOAD,
                                MAX_FLOWS: params.MAX_FLOWS,
                                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: "#podcast-notifications",
                        message: """The build ${currentBuild.fullDisplayName} has failed.! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"""
                    )
                }
            }
        }
    }
}