pipeline {
    agent any

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

    parameters {
        string(name: 'SKIP', defaultValue: '0', description: 'How many days back should we start processing?')
        string(name: 'DAYS', defaultValue: '1', description: 'Number of days to process')
        choice(name: 'ENVIRONMENT', choices: ['qa', 'prod'], description: 'The environment to run against.')
        choice(name: 'SOURCE', choices: ['Monthly', 'Weekly', 'Daily'], description: "Source or the report's date type.")
        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')
        choice(name: 'VENDOR_NAME', choices: ['SME', 'POD_SUB_LLC'], description: 'Name of the vendor for which data needs to be ingested')
        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 {
                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/apple_podcasts_subscription_events_monthly/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: "${params.DAYS}",
                                SKIP: "${params.SKIP}",
                                SOURCE: "${params.SOURCE}",
                                RELOAD: "${params.RELOAD}",
                                MAX_FLOWS: "${params.MAX_FLOWS}",
                                VENDOR_NAME: "${params.VENDOR_NAME}"
                            ]
                        )
                    }
                }
            }
        }
    }
    post {
        failure {
            script {
                if (params.ENVIRONMENT == 'prod') {
                    slackSend (
                        color: "danger",
                        channel: "#data",
                        message: """The build ${currentBuild.fullDisplayName} has failed.! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"""
                    )
                }
            }
        }
    }
}