String GITHUB_REPOSITORY = 'ows-assets'
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'
String BUILD_ROLE = 'qa-ows-assets-integration-test-role'
String SESSION_NAME = 'qa-ows-assets-integration-test'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2022-42969', // The py library through 1.11.0 for Python allows remote attackers to conduct a ReDoS (Regular expression Denial of Service)
                      // attack via a Subversion repository with crafted info data, because the InfoSvnCommand argument is mishandled.
                      // Note: This has been disputed by multiple third parties as not being reproducible and they argue
                      // this is not a valid vulnerability.",
    'CVE-2025-9086',  // curl vulnerability
    'CVE-2026-5773',  // curl vulnerability in Debian 12 base image; no upstream fix yet
    'CVE-2025-45768', // pyjwt weak-encryption concern; disputed by maintainer (key length is an application-level
                      // responsibility, not the library's); no patch planned.
                      // https://github.com/jpadilla/pyjwt/issues/1098
]

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, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).'
        )
        booleanParam(
            name: 'VERIFY_BUILD',
            defaultValue: false,
            description: 'Force build and test step to verify health.'
        )
    }

    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') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Build Test and Scan') {
            when {
                expression { isPullRequest() || params.VERIFY_BUILD }
            }
            environment {
                COMPOSE_PROJECT_NAME = "${env.BUILD_TAG.toLowerCase()}"
            }
            parallel {
                stage('Unit Tests and Style Checks') {
                    steps {
                        withEcr {
                            sh 'mkdir coverage'
                            sh 'chmod a+w coverage'
                            sh 'docker compose down --remove-orphans'
                            sh 'cp .env.shadow .env'
                            sh 'docker compose run --build --name ows-assets-unit-lint unit-lint'
                        }
                    }
                    post {
                        always {
                            sh 'docker cp ows-assets-unit-lint:/var/app/pyunit.xml ./pyunit.xml || true'
                            sh 'docker cp ows-assets-unit-lint:/var/app/coverage.xml ./coverage.xml || true'
                            sh 'sed -i.bak "s?<source>/var/app/assets</source>?<source>$$(pwd)/assets</source>?g" coverage.xml'
                        	sh 'rm -rf coverage.xml.bak'

                            xunit tools: [
                                JUnit(
                                    pattern: 'pyunit.xml',
                                    deleteOutputFiles: true,
                                    failIfNotNew: true,
                                    stopProcessingIfError: true
                                )
                            ]
                            recordCoverage(
                                tools: [
                                    [
                                        parser: 'COBERTURA',
                                        pattern: 'coverage.xml'
                                    ]
                                ],
                                enabledForFailure: true,
                                failOnError: true,
                                sourceDirectories: [[path: "assets"]]
                            )
                        }
                        cleanup {
                            sh 'docker compose down --remove-orphans'
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Sonar Scan and Analysis') {
                    steps {
                        sonarScan(
                            project: GITHUB_REPOSITORY,
                            language: 'py'
                        )
                    }
                }
                stage('Create and Docker Scan a Release') {
                    steps {
                        dockerToEcr(
                            awsRegions: AWS_REGIONS,
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: GITHUB_REPOSITORY,
                            imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                            dockerBuildTarget: 'deploy',
                            dockerBuildCacheDisabled: false
                        )
                        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 { !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 { !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('Integration Tests') {
           when {
               expression { !isPullRequest() }
           }
           steps {
               withEcr {
                   withSecrets(
                       awsAccountId: PROD_ACCOUNT_ID,
                       awsRole: BUILD_ROLE,
                       secrets: [
                           [id: 'qa/ows-assets/AUTOMATION_QA_DB_PASS', environmentVariable: 'QA_DB_PASS'],
                           [id: 'qa/ows-assets/AUTOMATION_DB_CLIENT_PASS', environmentVariable: 'DB_CLIENT_PASS']
                   ]) {
                       withAWS(
                           role: BUILD_ROLE,
                           roleAccount: QA_ACCOUNT_ID,
                           roleSessionName: SESSION_NAME,
                           useNode: true
                       ) {
                           sh 'cp tests/integration/.env.shadow .env && docker compose run --build --rm integration'
                       }
                   }
               }
           }
           post {
               cleanup {
                   sh 'docker compose down --remove-orphans'
               }
           }
        }
        stage('E2E Tests') {
            when {
                expression { !isPullRequest() }
            }
            environment {
                TAGS = "@${GITHUB_REPOSITORY.replaceAll('-', '_')}"
            }
            steps {
               playwrightTests tags: env.TAGS
            }
        }
        stage('Deploy to Prod') {
            when {
                expression { 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.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'
}
