String GITHUB_REPOSITORY = 'ows-store'
String ECR_ACCOUNT_ID = '437795906767'
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 INTEGRATION_TEST_ROLE = 'qa-ows-store-test-role'
String SESSION_NAME = 'qa-ows-store-integration-test'
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.'
        )
        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: 'RUN_E2E_TESTS',
            defaultValue: true,
            description: 'Whether or not to run e2e tests.'
        )
        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('Build Test and Scan') {
            when {
                expression { isPullRequest() || params.VERIFY_BUILD }
            }
            environment {
                COMPOSE_PROJECT_NAME = "${env.BUILD_TAG.toLowerCase()}"
            }
            parallel {
                stage('Sonar Scan and Analysis') {
                    steps {
                        script {
                            echo "Running Sonar Scan for ${GITHUB_REPOSITORY}"
                            sonarScan(
                                project: GITHUB_REPOSITORY,
                                language: 'py'
                            )
                        }
                    }
                }
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }
                stage('Unit Tests and Style Checks') {
                    steps {
                        withEcr {
                            sh 'docker compose down --remove-orphans'
                            sh 'cp .env.shadow .env'
                            sh 'docker compose run --build --name ows-store-unit-lint unit-lint'
                        }
                    }
                    post {
                        always {
                            sh 'docker cp ows-store-unit-lint:/var/app/pyunit.xml ./pyunit.xml || true'
                            sh 'docker cp ows-store-unit-lint:/var/app/coverage.xml ./coverage.xml || true'
	                        sh 'sed -i.bak "s?<source>/var/app/store</source>?<source>$$(pwd)/store</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: "store"]]
                            )
                        }
                        cleanup {
                            sh 'docker compose down --remove-orphans'
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                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() }
            }
            environment {
                QA_BASE_URL = 'https://qa-ows-store.theorchard.io'
            }
            steps {
                withEcr {
                    withAWS(role: INTEGRATION_TEST_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        sh 'docker compose run --rm --build integration'
                    }
                }
            }
            post {
                cleanup {
                    sh 'docker compose down --remove-orphans'
                }
            }
        }
        stage('E2E Tests') {
            when {
                expression { params.RUN_E2E_TESTS && !isPullRequest() }
            }
            environment {
                TAGS = "@ows_store"
            }
            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'
}
