String GITHUB_REPOSITORY = 'ows-abacus-account'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#abacus-devs'
String QA_ACCOUNT_ID = '989790945997'
String QA_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
String UAT_ACCOUNT_ID = '989790945997'
String UAT_DEPLOYMENT_ROLE = 'uat-jenkins-pipeline-deploy-role'
String INTEGRATION_TEST_ROLE = 'qa-ows-abacus-account-test-role'
String SESSION_NAME = 'qa-ows-abacus-account-integration-test'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
List<String> VULNERABILITIES_TO_IGNORE = []

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        booleanParam(name: 'RUN_E2E_TESTS_ONLY', defaultValue: false, description: 'Check this to <b>just</b> run the E2E tests. No other stages will be run, regardless of other parameter values.')
        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.')
    }

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

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                withEcr {
                    sh 'make ci_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: "abacus_account"]])
                }
                cleanup {
                    sh 'make ci_unit_lint_clean'
                }
            }
        }
        stage('Static Application Security Tests') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py'
            }
        }
        stage('Create a Release') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    dockerBuildTarget: 'deploy'
            }
        }
        stage('Deploy to QA') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
            }
        }
        stage('Scan Docker Image') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT, failBuild: false, vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
            }
        }
        stage('Integration Tests') {
            when {
                anyOf {
                    allOf {
                        branch 'master'
                        expression { !params.RUN_E2E_TESTS_ONLY }
                    }
                    allOf {
                        expression { env.GITHUB_COMMENT =~ 'run integration tests' }
                        expression { !params.RUN_E2E_TESTS_ONLY }
                    }
                }
            }
            steps {
                withEcr {
                    withAWS(role: INTEGRATION_TEST_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        withDatadogTestOptimizationEnv {
                            sh 'make ci_test_integration'
                        }
                    }
                }
            }
            post {
                always {
                    sh 'make ci_test_integration_clean'
                }
            }
        }
         stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                TAGS = "@ows_abacus_account"
            }
            steps {
                sleep(10)
                // e2eTests tags: env.TAGS, envVars: [setupMakeCommand: 'normalizeArtRelationsVendor']
                playwrightTests tags: env.TAGS, pnpmSetupScriptName: 'normalize-art-relations-vendor'
            }
        }
        stage('Deploy to UAT') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                fargateDeploy environment: 'uat', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: UAT_ACCOUNT_ID, awsDeploymentRoleName: UAT_DEPLOYMENT_ROLE
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }
            steps {
                fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                datadogSoftwareCatalogPublish()
            }
        }
    }

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