String GITHUB_REPOSITORY = 'bulkupload'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#security-team'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
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: true, description: 'Whether or not to deploy to prod.')
        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('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            steps {
                withCredentials([string(credentialsId: 'composer-github-auth', variable: 'GITHUB_AUTH')]) {
                    withEnv([
                        "APPLICATION_ENV=testing",
                        "ENVIRONMENT=testing",
                        "PHP_DISPLAY_ERRORS=true"
                    ]) {
                        withEcr {
							sh 'make ci_unit_lint'
                        }
                    }
                }
            }
            post {
                always {
                    script {
                        try {
                            junit allowEmptyResults: true, testResults: '**/build/logs/phpunit*.xml'
                        } catch (err) {
                            echo "JUnit publish skipped/failed: ${err}"
                        }

                        try {
                            recordCoverage(
                                tools: [[parser: 'CLOVER', pattern: 'build/logs/phpunit.coverage.xml']],
                                enabledForFailure: true,
                                failOnError: false,
                                sourceDirectories: [[path: 'reporting']]
                            )
                        } catch (err) {
                            echo "Coverage recording skipped/failed: ${err}"
                        }

                        try {
                            publishHTML([
                                reportDir: 'build/coverage',
                                reportFiles: 'index.html',
                                reportName: 'Clover Coverage',
                                keepAll: true,
                                alwaysLinkToLastBuild: true
                            ])
                        } catch (err) {
                            echo "HTML coverage publish skipped/failed: ${err}"
                        }
                    }
                }
                cleanup {
                    sh 'make ci_unit_lint_clean'
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'php'
            }
        }
        stage('Create a Release') {
            when {
                branch 'master'
            }
            steps {
                withCredentials([string(credentialsId: 'composer-github-auth', variable: 'GITHUB_AUTH')]) {
                    dockerToEcr awsRegions: AWS_REGIONS,
                        ecrAccountId: ECR_ACCOUNT_ID,
                        imageName: GITHUB_REPOSITORY,
                        imageTag: env.GIT_COMMIT,
                        dockerBuildSecrets: [[id: 'github_auth', env: 'GITHUB_AUTH']],
                        dockerBuildTarget: 'deploy'
                }
            }
        }
        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: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_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 {
        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()
        }
    }
}