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.')
        choice(name: 'REPORT', choices: ['ALL', 'consumption', 'production'], description: 'Report type to process.')
        string(name: 'DAYS', defaultValue: '3', description: 'Number of days to process going backwards.')
        string(name: 'SKIP', defaultValue: '1', description: 'How many days back to start processing.')
        string(name: 'CONTEXT_DATE', defaultValue: '', description: 'Optional single date to run (YYYY-MM-DD). Overrides DAYS/SKIP.')
        choice(name: 'RELOAD', choices: ['None', 'True'], description: '"True" - reset all statuses and re-download/reload files for the date range. "None" - normal incremental processing.')
        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 H/2 * * * % ENVIRONMENT=prod;SKIP=1;DAYS=3;REPORT=consumption
                H H/2 * * * % ENVIRONMENT=prod;SKIP=1;DAYS=3;REPORT=production
            '''
        )
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                script {
                    currentBuild.displayName = "#${currentBuild.number} [${params.ENVIRONMENT}] ${params.REPORT}"
                }
                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/meta_daily/exec.py',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: params.ENVIRONMENT,
                                REPORT: params.REPORT,
                                SKIP: params.SKIP,
                                DAYS: params.DAYS,
                                CONTEXT_DATE: params.CONTEXT_DATE,
                                RELOAD: params.RELOAD,
                                FEED_INGESTION_TABLE: "${params.ENVIRONMENT}_feed_ingestion_status",
                                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} was aborted! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"
                    )
                }
            }
        }
    }
}
