String GITHUB_REPOSITORY = 'swf-activity-detector'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#notifications'
String SLACK_DATA_PLATFORM_CHANNEL = '#data-alerts'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'


pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: false, description: 'Whether or not to deploy to prod. PLEASE CHECK ACTIVE EXECUTIONS https://us-east-1.console.aws.amazon.com/swf/v2/home?region=us-east-1#/domains/prod_activity_detector/')
        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') {
            steps {
                complianceChecks()
            }
        }
        stage('ECR login') {
            steps {
                sh """
                    aws ecr get-login-password --region ${AWS_REGIONS[0]} | docker login --username AWS --password-stdin ${ECR_ACCOUNT_ID}.dkr.ecr.${AWS_REGIONS[0]}.amazonaws.com
                """
            }
        }
        stage('Unit Tests and Style Checks') {
            agent {
                dockerfile {
                    additionalBuildArgs "--target tests"
                    args "-v ${PWD}:/var/app"
                    reuseNode true
                }
            }
            steps {
                sh 'make check'
            }
            post {
                always {
                    xunit tools: [JUnit(pattern: 'pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                    recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'coverage.xml']], enabledForFailure: true, failOnError: true)
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py', exclusions: 'tests/**'
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                 datadogSoftwareCatalogValidate()
            }
        }
        stage('Create a Release') {
            when {
                branch 'master'
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                    imageTag: env.GIT_COMMIT, dockerBuildTarget: 'main'
            }
        }
        stage('Scan Docker Image') {
            when {
                branch 'master'
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                 imageTag: env.GIT_COMMIT, failBuild: false
            }
        }
        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,
                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            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 {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                    slackNotify channel: SLACK_DATA_PLATFORM_CHANNEL
                }
            }
        }
    }
}
