String GITHUB_REPOSITORY = 'youtube-video-claiming'
String SLACK_NOTIFICATIONS_CHANNEL = '#security-team'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String QA_ACCOUNT_ID = '311141540202'
String QA_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
String PROD_ACCOUNT_ID = '710271914708'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-pipeline-deploy-role'
Integer CRON_UPDATE_TIMEOUT = 1800

BACON_SERVICES = [
    [serviceName: 'activities_q_population', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'manually_submitted_video_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'video_table_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'activities_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'video_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'tracks_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'asset_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'ownership_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'asset_match_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'claims_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
    [serviceName: 'references_q_consumer', deployType: 'UPDATE_SERVICE', verifyMode: 'TASK_RUNNING', updateTimeout: CRON_UPDATE_TIMEOUT],
]

pipeline {
    agent any

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

    parameters {
        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: 'DEPLOY_TO_PROD',
            defaultValue: true,
            description: 'Whether or not to deploy to prod.'
        )
    }

    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 Definitions') {
            steps {
                script {
                    parallel(BACON_SERVICES.collectEntries {service ->
                        [
                            (service.serviceName): {
                                echo "Validating Software Catalog definition for ${service.serviceName}"
                                datadogSoftwareCatalogValidate(serviceDefinitionFilePath: "software_catalog/${service.serviceName}.yaml")
                            }
                        ]
                    })
                }
            }
        }
        stage('Unit tests and Style Checks') {
            steps {
                withCredentials([string(credentialsId: 'composer-github-auth', variable: 'GITHUB_AUTH')]) {
                    withEcr {
                        sh 'docker compose up --exit-code-from unit-lint --abort-on-container-exit --build unit-lint'
                    }
                }
            }
            post {
                always {
                    sh 'docker compose down'
                    xunit(
                        tools: [
                            PHPUnit(
                                pattern: 'build/coverage/phpunit.xml',
                                deleteOutputFiles: true,
                                failIfNotNew: true,
                                stopProcessingIfError: true
                            )
                        ]
                    )
                    clover(
                        cloverReportDir: 'build/coverage',
                        cloverReportFileName: 'phpunit.coverage.xml',
                        healthyTarget: [methodCoverage: 70, conditionalCoverage: 80, statementCoverage: 80],
                        unhealthyTarget: [methodCoverage: 0, conditionalCoverage: 0, statementCoverage: 0],
                        failingTarget: [methodCoverage: 0, conditionalCoverage: 0, statementCoverage: 0]
                    )
                    recordCoverage(
                        tools: [[parser: 'CLOVER', pattern: 'build/coverage/phpunit.coverage.xml']],
                        enabledForFailure: true,
                        failOnError: false
                    )
                    publishHTML([
                        allowMissing: true,
                        alwaysLinkToLastBuild: true,
                        keepAll: true,
                        reportDir: 'build/coverage/html-coverage',
                        reportFiles: 'index.html',
                        reportName: 'Clover Coverage'
                    ])
                    junit allowEmptyResults: true, testResults: 'build/coverage/phpunit.xml'
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests(v2: true)
            }
        }
        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 {
                script {
                    parallel(BACON_SERVICES.collectEntries {service ->
                        [
                            (service.serviceName): {
                                fargateDeploy environment: 'qa',
                                    awsRegions: AWS_REGIONS,
                                    gitCommit: env.GIT_COMMIT,
                                    serviceName: service.serviceName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    imageNameOverride: GITHUB_REPOSITORY,
                                    verifyMode: service.verifyMode ?: 'EXIT_CODE',
                                    awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                    awsDeploymentRoleName: QA_DEPLOYMENT_ROLE,
                                    deployType: service.deployType,
                                    forceScaleOut: service.forceScaleOut,
                                    updateTimeout: service.updateTimeout ?: 300
                            }
                        ]
                    })
                }
            }
        }
        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(BACON_SERVICES.collectEntries {service ->
                        [
                            (service.serviceName): {
                                fargateDeploy environment: 'prod',
                                    awsRegions: AWS_REGIONS,
                                    gitCommit: env.GIT_COMMIT,
                                    serviceName: service.serviceName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    imageNameOverride: GITHUB_REPOSITORY,
                                    verifyMode: service.verifyMode ?: 'EXIT_CODE',
                                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                    awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE,
                                    deployType: service.deployType,
                                    forceScaleOut: service.forceScaleOut,
                                    updateTimeout: service.updateTimeout ?: 300
                            }
                        ]
                    })
                }
            }
        }
        stage('Publish Software Catalog Definitions') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(BACON_SERVICES.collectEntries {service ->
                        [
                            (service.serviceName): {
                                echo "Publishing Software Catalog definition for ${service.serviceName}"
                                datadogSoftwareCatalogPublish(serviceDefinitionFilePath: "software_catalog/${service.serviceName}.yaml")
                            }
                        ]
                    })
                }
            }
        }
    }

    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()
        }
    }
}
