import groovy.transform.Field

String GITHUB_REPOSITORY = 'ows-pdp'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String AWS_REGION = "us-east-1"
String SLACK_NOTIFICATIONS_CHANNEL = '#permissions-platform-alerts'
String QA_ACCOUNT_ID = '591204808501'
String QA_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
String QA_PDP_INTEGRATION_TEST_ROLE = "qa-pdp-integration-test-role"
String QA_DOMAIN_NAME = "qa-ows-pdp.theorchard.io"
String PROD_ACCOUNT_ID = '031099521156'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-pipeline-deploy-role'
String SESSION_NAME = "qa-pdp-integration-test"
String QA_REDIS_URL = "rediss://master.qa-pp-elasticache.cjuu9r.use1.cache.amazonaws.com:6379"
String PROD_REDIS_URL = "rediss://master.prod-pp-elasticache.ksc0ec.use1.cache.amazonaws.com:6379"
String CACHE_USE_REDIS = true
@Field String CERBOS_DIR = 'cerbos'
String CERBOS_IMAGE_NAME = 'cerbos'
List<String> VULNERABILITIES_TO_IGNORE = [
    "CVE-2025-45768",  // pkg:pypi latest version (The latest version has this vuln: '2.12.1')
    "CVE-2026-33164",  // pkg:deb/debian/libde265@1.0.11
]

pipeline {
    agent {
        label 'aws'
    }

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        booleanParam(name: 'FORCE_SEED_POLICY_METADATA_CACHE', defaultValue: false, description: 'Force re-seed the cerbos_policy_metadata Redis key from the most recently deployed commit, even if no policy files changed.')
        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.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Build Test and Scan') {
            parallel {
                stage('Validate Software Catalog Definitions') {
                    steps {
                        datadogSoftwareCatalogValidate()
                        datadogSoftwareCatalogValidate(servicePath: CERBOS_DIR)
                    }
                }

                stage('Unit Tests and Style Checks') {
                    environment {
                        COMPOSE_PROJECT_NAME = "${env.BUILD_TAG.toLowerCase()}"
                    }
                    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: "pdp"]])
                        }
                        cleanup {
                            sh 'make ci_unit_lint_clean'
                        }
                    }
                }

                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }

                stage('Sonar Scan and Analysis') {
                    when {
                        branch 'master'
                    }
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'py'
                    }
                }

                stage('Create and Scan a Release') {
                    steps {
                        dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                            dockerBuildTarget: 'deploy'
                        dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: CERBOS_IMAGE_NAME, imageTag: env.GIT_COMMIT,
                            dockerBuildContext: "./${CERBOS_DIR}", dockerBuildFile: "./${CERBOS_DIR}/Dockerfile"
                        dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                    }
                }
            }
        }
        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                withEcr {
                    withAWS(role: QA_PDP_INTEGRATION_TEST_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        sh 'make ci_test_integration'
                    }
                }
            }
            post {
                cleanup {
                    sh 'make down'
                }
            }
        }
        stage('Deploy to QA Fargate in parallel') {
            when {
                branch 'master'
            }
            parallel {
                stage("Deploy ows-pdp to QA") {
                    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("Deploy cerbos to QA") {
                    when {
                        allOf {
                            expression { isCerbosPolicyUpdated() == true }
                        }
                    }
                    steps {
                        fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: "cerbos",
                            ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                    }
                }
            }
        }
        stage('Bludgeon QA Cache') {
            when {
                allOf {
                    branch 'master'
                    expression { isCerbosPolicyUpdated() == true }
                }
            }
            steps {
                withEcr {
                    withEnv([
                        "QA_DEPLOYMENT_ROLE=${QA_DEPLOYMENT_ROLE}",
                        "REDIS_URL=${QA_REDIS_URL}",
                        "CACHE_USE_REDIS=${CACHE_USE_REDIS}"
                    ]) {
                        withAWS(role: QA_DEPLOYMENT_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                            sh 'make bludgeon_cached_cerbos_decisions'
                        }
                    }
                }
            }
        }
        stage('Seed QA Policy Metadata Cache') {
            when {
                allOf {
                    branch 'master'
                    expression { isCerbosPolicyUpdated() == true }
                }
            }
            steps {
                withEcr {
                    withEnv([
                        "QA_DEPLOYMENT_ROLE=${QA_DEPLOYMENT_ROLE}",
                        "REDIS_URL=${QA_REDIS_URL}",
                        "CACHE_USE_REDIS=${CACHE_USE_REDIS}"
                    ]) {
                        withAWS(role: QA_DEPLOYMENT_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: 'qa-seed-policy-metadata-cache', useNode: true) {
                            sh 'make seed_policy_metadata_cache'
                        }
                    }
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            steps {
                playwrightTests tags: '@ows_pdp'
            }
        }
        stage('K6 Load Tests') {
            when {
                branch 'master'
            }
            steps {
                // run load tests against QA environment, at the moment we don't want to wait for
                // the tests to complete and propagate errors if any
                k6Tests backendService: 'ows-pdp', testFile: 'api.ts', waitCompletion: false, propagateFailure: false
            }
        }
        stage('Deploy to Prod Fargate in parallel') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            parallel {
                stage("Deploy ows-pdp to Prod") {
                    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
                        datadogSoftwareCatalogPublish()
                    }
                }
                stage("Deploy cerbos to Prod") {
                    steps {
                        fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: "cerbos",
                            ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                        datadogSoftwareCatalogPublish(servicePath: CERBOS_DIR)
                    }
                }
            }
        }
        stage('Bludgeon Prod Cache') {
            when {
                allOf {
                    branch 'master'
                    expression { isCerbosPolicyUpdated() == true }
                }
            }
            steps {
                withEcr {
                    withEnv([
                        "PROD_DEPLOYMENT_ROLE=${PROD_DEPLOYMENT_ROLE}",
                        "REDIS_URL=${PROD_REDIS_URL}",
                        "CACHE_USE_REDIS=${CACHE_USE_REDIS}"
                    ]) {
                        withAWS(role: PROD_DEPLOYMENT_ROLE, roleAccount: PROD_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                            sh 'make bludgeon_cached_cerbos_decisions'
                        }
                    }
                }
            }
        }
        stage('Seed Prod Policy Metadata Cache') {
            when {
                allOf {
                    branch 'master'
                    expression { isCerbosPolicyUpdated() == true }
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                withEcr {
                    withEnv([
                        "PROD_DEPLOYMENT_ROLE=${PROD_DEPLOYMENT_ROLE}",
                        "REDIS_URL=${PROD_REDIS_URL}",
                        "CACHE_USE_REDIS=${CACHE_USE_REDIS}"
                    ]) {
                        withAWS(role: PROD_DEPLOYMENT_ROLE, roleAccount: PROD_ACCOUNT_ID, roleSessionName: 'prod-seed-policy-metadata-cache', useNode: true) {
                            sh 'make seed_policy_metadata_cache'
                        }
                    }
                }
            }
        }
    }

    post {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}

/**
 * isCerbosPolicyUpdated returns True if
 * cerbos policies, schemas, etc. have been updated.
 * Else, isCerbosPolicyUpdated returns False.
 */
def isCerbosPolicyUpdated() {
    def modifiedPaths = getModifiedPaths()
    for (modifiedPath in modifiedPaths) {
        if (modifiedPath.startsWith("${CERBOS_DIR}/")) {
            return true
        }
    }
    return false
}
