String GITHUB_REPOSITORY = 'ows-account'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#accounts-team-alerts'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String QA_DOMAIN_NAME = "qa-ows-account.theorchard.io"
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String QA_OWS_ACCOUNT_INTEGRATION_TEST_ROLE = "qa-ows-account-integration-test-role"
String SESSION_NAME = "qa-ows-account-integration-test"

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') {
            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: "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('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
            }
        }
        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('Integration Tests') {
            when {
                allOf {
                    branch 'master'
                    expression { !params.RUN_E2E_TESTS_ONLY }
                }
            }

            steps {
                withEcr {
                    withAWS(role: QA_OWS_ACCOUNT_INTEGRATION_TEST_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        sh 'make ci_test_integration'
                    }
                }
            }

            post {
                cleanup {
                    sh 'make ci_test_integration_clean'
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                // Using smoke tests for now, coverage needs to be reviewed
                TAGS = "@qa_smoke"
            }
            steps {
                playwrightTests tags: env.TAGS, slackNotificationChannels: [SLACK_NOTIFICATIONS_CHANNEL]
            }
        }
        stage('Load Tests') {
            when {
                branch 'master'
            }
            steps {
                // run load tests against QA environment, at the moment we don't want to wait for
                // the tests to complete and propagate errors if any
                loadTests host: QA_DOMAIN_NAME, waitCompletion: false, propagateFailure: false
            }
        }
        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 {
        fixed {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        failure {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
