String GITHUB_REPOSITORY = 'ows-product-store-mapping'
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-9086',  // curl vulnerability
]

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(
            '''
            @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 'make ci_unit_lint'
                        }
                    }
                    post {
                        always {
                            xunit(
                                tools: [
                                    JUnit(
                                        pattern: 'build/pyunit.xml',
                                        deleteOutputFiles: true,
                                        failIfNotNew: true,
                                        stopProcessingIfError: true
                                    )
                                ]
                            )
                            recordCoverage(
                                tools: [
                                    [
                                        parser: 'COBERTURA',
                                        pattern: 'build/coverage.xml'
                                    ]
                                ],
                                enabledForFailure: true,
                                failOnError: true,
                                sourceDirectories: [
                                    [
                                        path: "product_store_mapping"
                                    ]
                                ]
                            )
                        }
                        cleanup {
                            sh 'make ci_unit_lint_clean'
                        }
                    }
                }
                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('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'
}
