// Pipeline script for: https://scheduler.theorchard.io/job/pdp-qa-refresh/
String SERVICE_NAME = "pdp-backfill"
String QA_ACCOUNT_ID = "591204808501"
String QA_RUN_PDP_BACKFILL_TASK_ROLE = "qa-pdp-backfill-task-run-role"
String QA_RUN_DYNAMODB_REFRESH_SFN = "qa-pdp-backfill-dynamodb-refresh-sfn-run-role"
String DYNAMODB_REFRESH_SFN_ARN = "arn:aws:states:us-east-1:591204808501:stateMachine:qa-dynamodb-refresh-sfn"
String QA_VPC_NAME = "qa-terraform-aws-vpc"
String QA_BUCKET = "qa-pdp-backfill"
String QA_MANIFEST_FILE_KEY = "pdp_qa_refresh/manifest.json"

String SESSION_NAME = "pdp-qa-refresh-jenkins-scheduler"
String AWS_REGION = "us-east-1"
String SLACK_NOTIFICATIONS_CHANNEL = "#permissions-platform-alerts"

pipeline {
    agent {
        label 'aws && agent'
    }
    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }
    parameters {
        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.')
        choice(name: 'Environment', choices: ['qa'], description: 'Environment to perform refresh for')
        choice(name: 'MODE', choices: ['apply_manifest_only', 'full_refresh'], description: 'Choose apply_manifest_only to re-apply manifest.json (no downtime); full_refresh to restore from last snapshot of prod and re-apply manifest.json (downtime)')
        string(name: 'MANIFEST_FILE_KEY', defaultValue: QA_MANIFEST_FILE_KEY, description: 'Key of the manifest.json file in the qa-pdp-backfill bucket.')
    }
    stages {
        stage('Load Global Libraries') {
            steps {
                library "jenkins-global-libraries@${params.GLOBAL_LIBRARIES_VERSION}"
            }
        }
        stage('Full Refresh') {
            when {
                expression { params.MODE == 'full_refresh' }
            }
            steps {
                withEcr{
                    withAWS(role: QA_RUN_DYNAMODB_REFRESH_SFN, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        sh "docker compose run --rm --build pdp-backfill-local backfill invoke_sfn --state-machine-arn ${DYNAMODB_REFRESH_SFN_ARN}"
                        sh "echo 'You can follow the state machine executions at https://us-east-1.console.aws.amazon.com/states/home?region=us-east-1#/statemachines/view/arn:aws:states:us-east-1:591204808501:stateMachine:qa-dynamodb-refresh-sfn'"
                    }
                }
            }
        }
        stage('Apply Manifest Only') {
            when {
                expression { params.MODE == 'apply_manifest_only' }
            }
            environment {
                ACCOUNT_ID = "${QA_ACCOUNT_ID}"
                RUN_TASK_ROLE = "${QA_RUN_TASK_ROLE}"
                VPC_NAME = "${QA_VPC_NAME}"
                SERVICE_NAME = "${SERVICE_NAME}"
                CLUSTER_NAME = "qa-${SERVICE_NAME}"
                VERIFY_MODE = "EXIT_CODE"
            }
            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"]]])

                withEnv([
                    "AWS_DEFAULT_REGION=${AWS_REGION}",
                ]) {
                    withAWS(role: QA_RUN_PDP_BACKFILL_TASK_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        run_task("backfill,process,--bucket-name,${QA_BUCKET},--manifest-file,${params.MANIFEST_FILE_KEY}")
                    }
                }
            }
        }
    }

    post {
        always {
            script {
                slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
            }
        }
    }
}

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

        echo "ENVIRONMENT is \${Environment}"
        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}
        """
    }
}
