String GITHUB_REPOSITORY = 'auth0-m2m-config'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#permissions-platform-alerts'
String QA_ACCOUNT_ID = '591204808501'
String QA_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
String UAT_ACCOUNT_ID = '591204808501'
String UAT_DEPLOYMENT_ROLE = 'uat-jenkins-pipeline-deploy-role'
String PROD_ACCOUNT_ID = '031099521156'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-pipeline-deploy-role'
String QA_TASK_ROLE = 'qa-auth0-m2m-config-task-role'
List<String> VULNERABILITIES_TO_IGNORE = []

pipeline {
    agent {
        label 'aws'
    }

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        choice(name: 'DEPLOY_TO_PROD', choices: ['Yes', 'No'], description: 'Whether or not to deploy to prod.')
        choice(name: 'DEPLOY_TO_UAT', choices: ['Yes', 'No'], description: 'Whether or not to deploy to UAT.')
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag or Git revision.')
        booleanParam(name: 'FAIL_BUILD_ECR_SCAN', defaultValue: false, description: 'If ECR Scan fails/times out, fail the build.')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            steps {
                withEcr{
                    sh 'make ci_test_unit_lint'
                }
            }
            post {
                always {
                    xunit tools: [JUnit(pattern: 'build/pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                    recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'build/coverage.xml']], enabledForFailure: true, failOnError: true, sourceDirectories: [[path: "m2mconfig"]])
                }
                cleanup {
                    sh 'make ci_clean_unit_lint'
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py'
            }
        }
        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID,
                    imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    dockerBuildTarget: 'deploy'
            }
        }
        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                withEcr{
                    withAWS(
                        role: QA_TASK_ROLE,
                        roleAccount: QA_ACCOUNT_ID,
                        roleSessionName: 'auth0-m2m-config-integration-tests',
                        useNode: true
                    ) {
                        withSecrets(
                            awsAccountId: QA_ACCOUNT_ID,
                            awsRole: 'qa-assume-auth0-m2m-config',
                            secrets: [
                                [
                                    id: 'qa/auth0-m2m-config/M2M_AUTH0_CLIENT_CREDENTIALS',
                                    environmentVariable: 'AUTH0_M2M_CONFIG_CLIENT_CREDENTIALS'
                                ],
                            ]
                        ) {
                            sh 'make ci_test_integration'
                        }
                    }
                }
            }
            post {
                cleanup {
                    sh 'make ci_clean_integration'
                }
            }
        }
        stage('Dry Run in QA') {
            when {
                branch 'master'
            }
            steps {
                withEcr {
                    sh 'docker compose -f docker-compose-deploy.yml pull'
                }
                withAWS(
                    role: QA_TASK_ROLE,
                    roleAccount: QA_ACCOUNT_ID,
                    roleSessionName: 'auth0-m2m-config-qa-dry-run',
                    useNode: true
                ) {
                    withSecrets(
                        awsAccountId: QA_ACCOUNT_ID,
                        awsRole: 'qa-assume-auth0-m2m-config',
                        secrets: [
                            [
                                id: 'qa/auth0-m2m-config/M2M_AUTH0_CLIENT_CREDENTIALS',
                                environmentVariable: 'AUTH0_M2M_CONFIG_CLIENT_CREDENTIALS'
                            ],
                        ]
                    ) {
                        sh 'SENTRY_DSN="https://cb5558b722b205a9bb2c3bbc2a87c91b@o22178.ingest.us.sentry.io/4507787474436096" \
                            AUTH0_DOMAIN=qa-orchard.auth0.com \
                            ENV=qa \
                            ALL_OR_ONE=all \
                            DRY_RUN=--dry-run \
                            OVERWRITE_SECRET=--overwrite-secret \
                                make docker_sync'
                    }
                }
            }
            post {
                cleanup {
                    sh 'docker compose -f docker-compose-deploy.yml down --remove-orphans'
                }
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, deployType: 'CREATE_TASK_DEFINITION',
                    awsDeploymentTargetAccountId: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                TAGS = "@frontend_auth0"
            }
            steps {
                sh 'echo "Disabled because @frontend_auth0 is irrelevant to auth0-m2m-config"'
                // e2eTests tags: env.TAGS
            }
            // post {
            //     regression {
            //         slackNotify channel: '#cypress-test-e2e-results'
            //     }
            //     fixed {
            //         slackNotify channel: '#cypress-test-e2e-results'
            //     }
            // }
        }
        stage('Scan Docker Image') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID,
                    imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
            }
        }
        stage('Deploy to UAT') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_UAT == 'Yes' }
                }
            }
            steps {
                fargateDeploy environment: 'uat', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, deployType: 'CREATE_TASK_DEFINITION',
                    awsDeploymentTargetAccountId: UAT_ACCOUNT_ID, awsDeploymentRoleName: UAT_DEPLOYMENT_ROLE
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, deployType: 'CREATE_TASK_DEFINITION',
                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
            }
        }
        stage('Publish Software Catalog Definition') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
