String GITHUB_REPOSITORY = 'ows-metadata'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#distro-build-alerts'
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'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2025-64500',  // Symfony vulnerabilities is here to stay indefinitely
    'CVE-2026-53151',
    'CVE-2026-31419',
    'CVE-2026-46054',
    'CVE-2026-46242',
    // libraw CVEs from the docker-parent-images:debian13-php84 base image; no
    // fixed version in Debian trixie yet, so apt upgrade can't clear them.
    // Remove once trixie ships a patched libraw (> 0.21.4-2):
    //  https://security-tracker.debian.org/tracker/source-package/libraw
    'CVE-2026-20884',
    'CVE-2026-20889',
    'CVE-2026-21413',
    'CVE-2026-24450',
    'CVE-2026-24660'
]

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.'
        )
        booleanParam(
            name: 'VERIFY_BUILD',
            defaultValue: false,
            description: 'Force build and test step to verify health.'
        )
        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.*')
        parameterizedCron(env.BRANCH_NAME == 'master' ? '@weekly %DEPLOY_TO_PROD=false;VERIFY_BUILD=true' : '')
    }

    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('Build Test and Scan') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY && (isPullRequest() || params.VERIFY_BUILD) }
            }
            environment {
                COMPOSE_PROJECT_NAME = "${env.BUILD_TAG.toLowerCase()}"
            }
            parallel {
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }
                stage('Unit Tests and Style Checks') {
                    steps {
                        withCredentials([string(credentialsId: 'composer-github-auth', variable: 'COMPOSER_AUTH'),]) {
                            withEcr {
                                sh 'docker compose run --rm --build unit-lint'
                            }
                        }
                    }
                    post {
                        always {
                            sh 'docker compose down -v'
                            xunit(
                                tools: [
                                    PHPUnit(
                                        pattern: 'build/logs/phpunit.xml',
                                        deleteOutputFiles: true,
                                        failIfNotNew: true,
                                        stopProcessingIfError: true
                                    )
                                ]
                            )
                            clover(
                                cloverReportDir: 'build/logs',
                                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]
                            )
//                             sh 'rm -R build/logs'
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Sonar Scan and Analysis') {
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'php'
                    }
                }
                stage('Create and Docker Scan a Release') {
                    steps {
                        withCredentials([string(credentialsId: 'composer-github-auth', variable: 'COMPOSER_AUTH'),]) {
                            dockerToEcr(
                                awsRegions: AWS_REGIONS,
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: GITHUB_REPOSITORY,
                                imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                                dockerBuildSecrets: [
                                    [
                                        id: 'COMPOSER_AUTH',
                                        env: 'COMPOSER_AUTH'
                                    ]
                                ],
                                dockerBuildTarget: 'app'
                            )
                        }
                        dockerScan(
                            awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: GITHUB_REPOSITORY,
                            imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                        )
                    }
                }
            }
        }
        stage('Retag and Scan') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY && !isPullRequest() }
            }
            parallel {
                stage('Retag and Docker Scan a Release') {
                    steps {
                        script {
                            def prNumber = githubGetCommitPrs(
                                repo: GITHUB_REPOSITORY,
                                commitSha: env.GIT_COMMIT
                            )[0].number
                            retagEcrImage(
                                awsRegions: AWS_REGIONS,
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: GITHUB_REPOSITORY,
                                imageTag: 'PR-' + prNumber,
                                newTag: env.GIT_COMMIT
                            )
                            dockerScan(
                                awsRegion: AWS_REGIONS[0],
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: GITHUB_REPOSITORY,
                                imageTag: env.GIT_COMMIT,
                                vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                            )
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
            }
        }
        stage('Deploy to QA') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY && !isPullRequest() }
            }
            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('E2E Tests') {
            when {
                expression { !isPullRequest() }
            }
            environment {
                TAGS = "@ows_metadata"
            }
            steps {
                playwrightTests tags: env.TAGS
            }
        }
        stage('Deploy to Prod') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY && params.DEPLOY_TO_PROD && !isPullRequest() }
            }
            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
                )
            }
        }
        stage('Publish Software Catalog Definition') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY && params.DEPLOY_TO_PROD && !isPullRequest() }
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        regression {
            script {
                if (!isPullRequest()) {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (!isPullRequest()) {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}

def isPullRequest() {
    return env.BRANCH_NAME != 'master'
}
