pipeline {
    agent any

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

    parameters {
        string(name: 'SKIP', defaultValue: '1', description: 'How many days back should we start processing?')
        string(name: 'DAYS', defaultValue: '4', description: 'Number of days to process')
        choice(name: 'LICENSOR', choices: ['theorchard', 'smej'], description: 'Pick licensor.')
        string(name: 'MAX_CONCURRENT_FLOWS', defaultValue: '10', description: '10 for theorchard / 100 for smej')
        choice(name: 'ENVIRONMENT', choices: ['prod', 'qa'], description: 'The environment to run against.')
        booleanParam(name: 'RELOAD', defaultValue: false, description: 'when checked is sends to context "reload": "True"')
        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/8 * * * %ENVIRONMENT=prod;SKIP=1;DAYS=4;LICENSOR=theorchard;MAX_CONCURRENT_FLOWS=10
            H H/8 * * * %ENVIRONMENT=prod;SKIP=1;DAYS=4;LICENSOR=smej;MAX_CONCURRENT_FLOWS=100
            '''
        )
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                script {
                    def buildUser = env.BUILD_USER_ID ?: 'unknown'
                    currentBuild.displayName = "[${params.ENVIRONMENT}] ${params.LICENSOR} by ${buildUser}"
                }
                library "jenkins-global-libraries@master"
            }
        }
        stage('Run exec job') {
           when {
                expression {
                    params.ONLY_UPDATE_JOB == false
                }
            }
            steps {
                    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/awa/exec.py',
                            imageRepo: '086679231553.dkr.ecr.us-east-1.amazonaws.com/swf-feed-ingestion',
                            envVars: [
                                Environment: params.ENVIRONMENT,
                                DAYS: params.DAYS,
                                SKIP: params.SKIP,
                                RELOAD: params.RELOAD,
                                LICENSOR: params.LICENSOR,
                                MAX_CONCURRENT_FLOWS: params.MAX_CONCURRENT_FLOWS,

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