String QA_ACCOUNT_ID = "591204808501"
String QA_RUN_TASK_ROLE = "qa-auth0-m2m-config-task-run-role"
String QA_VPC_NAME = "qa-terraform-aws-vpc"

String UAT_ACCOUNT_ID = "591204808501"
String UAT_RUN_TASK_ROLE = "uat-auth0-m2m-config-task-run-role"
String UAT_VPC_NAME = "qa-terraform-aws-vpc"

String PROD_ACCOUNT_ID = "031099521156"
String PROD_RUN_TASK_ROLE = "prod-auth0-m2m-config-task-run-role"
String PROD_VPC_NAME = "prod-terraform-aws-vpc"

String SLACK_NOTIFICATIONS_CHANNEL = "#permissions-platform-alerts"

pipeline {
    agent {
        label 'aws && agent'
    }
    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }
    parameters {
        choice(name: 'Environment', choices: ['qa', 'prod', 'uat'], description: 'Environment to perform auth0-m2m-config for')
        choice(name: 'MODE', choices: ['one', 'all'], description: 'Sync one specific entry or all entries from m2m.json')
        string(name: 'ENTRY', description: 'Specific entry if using "one" MODE.')
        choice(name: "DRY_RUN", choices: ['--no-dry-run', '--dry-run'], description: 'Whether to run dry run.')
        choice(name: "OVERWRITE_SECRET", choices: ['--no-overwrite-secret', '--overwrite-secret'], description: 'Whether to overwrite secret.')
        choice(name: "ROTATE_AUTH0_CLIENT_CREDENTIALS", choices: ['--no-rotate-secret', '--rotate-secret'], description: 'CAUTION -- ADVANCED MODE: Whether to rotate the Auth0 Application\'s Client Credentials and save to AWS Secrets Manager (overwrite). If you do this for QA, you must immediately run with --no-rotate-secret, --overwrite-secret in UAT.')
        string(name: 'GLOBAL_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins global libraries to use. Can be a branch, tag or Git revision.')
    }
    environment {
        ACCOUNT_ID = "${params.Environment == "prod" ? PROD_ACCOUNT_ID : (params.Environment == "uat" ? UAT_ACCOUNT_ID : QA_ACCOUNT_ID)}"
        RUN_TASK_ROLE = "${params.Environment == "prod" ? PROD_RUN_TASK_ROLE : (params.Environment == "uat" ? UAT_RUN_TASK_ROLE : QA_RUN_TASK_ROLE)}"
        VPC_NAME = "${params.Environment == "prod" ? PROD_VPC_NAME : (params.Environment == "uat" ? UAT_VPC_NAME : QA_VPC_NAME)}"
        SERVICE_NAME = "auth0-m2m-config"
        CLUSTER_NAME = "${params.Environment}-${SERVICE_NAME}"
        VERIFY_MODE = "EXIT_CODE"
    }
    stages {
        stage('Load Global Libraries') {
            steps {
                library "jenkins-global-libraries@${params.GLOBAL_LIBRARIES_VERSION}"
            }
        }
        stage('Checkout python-deployment-utils') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '7c29b204-9e5b-45e0-bd0a-6535917c604f', url: "git@github.com:theorchard/python-deployment-utils.git"]]])
            }
        }
        stage('Run Sync All') {
            when {
                expression { params.MODE == 'all' }
            }
            steps {
                withAWS(role: RUN_TASK_ROLE, roleAccount: ACCOUNT_ID, roleSessionName: "m2mconfig-sync-all", useNode: true) {
                    run_task("sync,all,${params.Environment},${params.DRY_RUN},${params.OVERWRITE_SECRET},${params.ROTATE_AUTH0_CLIENT_CREDENTIALS}")
                }
            }
        }
        stage('Run Sync One') {
            when {
                expression { params.MODE == 'one' }
            }
            steps {
                withAWS(role: RUN_TASK_ROLE, roleAccount: ACCOUNT_ID, roleSessionName: "m2mconfig-sync-one", useNode: true) {
                    run_task("sync,one,${params.Environment},${params.ENTRY},${params.OVERWRITE_SECRET},${params.ROTATE_AUTH0_CLIENT_CREDENTIALS}")
                }
            }
        }
    }

    post {
        always {
            script {
                slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL,
                    message: "Run auth0-m2m-config task: m2mconfig sync ${params.MODE} ${params.Environment} ${params.ENTRY} ${params.DRY_RUN} ${params.OVERWRITE_SECRET} ${params.ROTATE_AUTH0_CLIENT_CREDENTIALS} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"
            }
        }
    }
}

def run_task(def command) {
    dir('fargate') {
        sh """
        set +x

        echo "VERIFY_MODE is \${VERIFY_MODE}"
        echo "ACCOUNT_ID is \${ACCOUNT_ID}"
        echo "RUN_TASK_ROLE is \${RUN_TASK_ROLE}"
        echo "VPC_NAME is \${VPC_NAME}"
        echo "CLUSTER_NAME is \${CLUSTER_NAME}"
        echo "SERVICE_NAME is \${SERVICE_NAME}"

        python3 -m venv venv
        . ./venv/bin/activate

        pip install -r requirements.txt

        set -x

        python -u run_fargate_task.py --command ${command}
        """
    }
}
