String GITHUB_REPOSITORY = 'ows-video'
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 = []

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.'
        )
        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: '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') {
            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 {
                        withEcr {
                            sh 'cp .env.shadow .env'
                            sh 'docker compose down --remove-orphans'
                            sh 'docker compose run --build --name ows-video-unit-lint unit-lint'
                        }
                    }
                    post {
                        always {
                            sh 'docker cp ows-video-unit-lint:/var/app/pyunit.xml ./pyunit.xml || true'
                            sh 'docker cp ows-video-unit-lint:/var/app/coverage.xml ./coverage.xml || true'
                            sh 'sed -i.bak "s?<source>/var/app/video</source>?<source>$$(pwd)/video</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: "video"
                                    ]
                                ]
                            )
                        }
                        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 { !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('Integration Tests') {
            when {
                expression { !params.RUN_E2E_TESTS_ONLY && !isPullRequest() }
            }
            steps {
                withEcr {
                    withAWS(
                        role: 'qa-ows-video-integration-tests',
                        roleSessionName: 'qa-ows-video-integration-tests',
                        useNode: true
                    ) {
                        sh 'docker compose run --rm --build integration'
                    }
                }
            }
            post {
                cleanup {
                    sh 'docker compose down --remove-orphans'
                }
            }
        }
        stage('Playwright E2E Tests') {
            when {
                expression { !isPullRequest() }
            }
            environment {
                TAGS = "@ows_video"
            }
            steps {
                playwrightTests(
                    tags: env.TAGS,
                    runtimeEnvironment: 'ecs'
                )
            }
        }
        stage('Deploy to Prod') {
            when {
                expression { !isPullRequest() && params.DEPLOY_TO_PROD && !params.RUN_E2E_TESTS_ONLY }
            }
            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 { !isPullRequest() && params.DEPLOY_TO_PROD && !params.RUN_E2E_TESTS_ONLY }
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }
    }

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

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