String GITHUB_REPOSITORY = 'lambda-nr-ownership-delivery'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#knr-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'

@groovy.transform.Field
List<String> functionsToBuild = null

// mapping function (lambda) names to the names of our ECR repos
// they're not all the same, unfortunately
// see: https://github.com/theorchard/terraform-infra/blob/0b7b9013d441a86cd714ce48d61fc03cc6b2de9f/qa/neighbouring-rights/ownership-delivery/variables.tf#L47
@groovy.transform.Field
final def lambdaRepoMaps = [ "order-populator": "order-populator",
  "template-data-loader": "template-loader",
  "output-file-builder": "output-builder",
  "order-finalizer": "order-finalizer",
  "ddex-generator": "ddex-generator",
  "ddex-compiler": "ddex-compiler",
  "contract-processor": "contracts",
  "order-recorder": "order-recorder",
  "coordinator": "coordinator",
  "output-file-builder": "output-builder",
  "orchard-history-filter": "orchard-history-filter",]

// TODO: Update/remove the affected dependencies
List<String> VULNERABILITIES_TO_IGNORE = [
    // These four come from the datadog-lambda-extension image (copied into /opt
    // via the Dockerfile). Vendor code with no user-controlled input reaching
    // these paths; not exploitable in our usage.
    'CVE-2025-62718', // axios in datadog-lambda-extension
    'CVE-2026-4800',  // lodash in datadog-lambda-extension
    'CVE-2026-33671', // picomatch in datadog-lambda-extension
    'CVE-2026-33750', // brace-expansion in datadog-lambda-extension

    'CVE-2026-27903', // minimatch
    'CVE-2026-27904', // minimatch
    'CVE-2026-29786', // tar
    'CVE-2026-31802'  // tar
]

def isFargate(name) {
    return name == 'output-file-builder' || name == 'ddex-compiler'
}

def getImageName(functionName) {
    def imageName = lambdaRepoMaps[functionName]
    if(isFargate(functionName)){
        return "fargate-nr-ownership-delivery-${functionName}"
    }
    if (imageName == "orchard-history-filter")
        return "lambda-nr-owndel-${imageName}";
    return "lambda-nr-ownership-delivery-${imageName}"
}

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        string(name: 'LAMBDA_FUNCTION_NAME', defaultValue: '', description: 'Name of the Lambda function to build and deploy')
        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).')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

    stages {
        stage('Checkout') {
            steps {
                script {
                    cleanWs()
                    def scmVars = checkout scm
                    // Set SCM vars as environment variables to replicate default checkout functionality
                    scmVars.each { k, v ->
                        env."${k}" = v
                    }
                }
            }
        }

        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Compliance Checks') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Compliance Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    complianceChecks()
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Validate Software Catalog Definition') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Validating Software Catalog Definition for ${functionName}"
                                datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        stage('Unit Tests and Style Checks') {
            environment {
                GITHUB_TOKEN = credentials('github_packages_token')
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Unit Tests and Style Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    sh "docker compose run --rm --build lint-and-test"
                                }
                            }
                        ]
                    })
                }
            }
            post {
                cleanup {
                    script {
                        parallel(getFunctionsToBuild().collectEntries { functionName ->
                            return [
                                (functionName): {
                                    echo "Cleaning up for ${functionName}"
                                    dir("lambda/${functionName}") {
                                        sh 'docker compose down -v'
                                    }
                                }
                            ]
                        })
                    }
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Static App Security Tests for ${functionName}"
                                sastTests(projectDir: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${GITHUB_REPOSITORY}"
                    sonarScan project: GITHUB_REPOSITORY, language: 'ts'
                }
            }
        }

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')]) {
                                    echo "Building for ${functionName}"
                                    if (isFargate(functionName)) {
                                        echo "Building Fargate image for ${functionName}"
                                        // for now, build fargate image separately from the lambda
                                        dockerToEcr awsRegions: AWS_REGIONS,
                                            ecrAccountId: ECR_ACCOUNT_ID,
                                            imageName: getImageName(functionName),
                                            imageTag: env.GIT_COMMIT,
                                            dockerBuildContext: "lambda/${functionName}",
                                            dockerBuildSecrets: [[id: 'github_token', env: 'GITHUB_TOKEN']],
                                            dockerBuildFile: "lambda/${functionName}/Dockerfile.fargate"
                                    } else {
                                        dockerToEcr awsRegions: AWS_REGIONS,
                                            ecrAccountId: ECR_ACCOUNT_ID,
                                            imageName: getImageName(functionName),
                                            imageTag: env.GIT_COMMIT,
                                            dockerBuildContext: "lambda/${functionName}",
                                            dockerBuildSecrets: [[id: 'github_token', env: 'GITHUB_TOKEN']],
                                            dockerBuildFile: "lambda/${functionName}/Dockerfile"
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Scanning Docker Images for ${functionName}"
                                dir("lambda/${functionName}") {
                                    dockerScan awsRegion: AWS_REGIONS[0],
                                        ecrAccountId: ECR_ACCOUNT_ID,
                                        imageName: getImageName(functionName),
                                        imageTag: env.GIT_COMMIT,
                                        vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Deploying to QA for ${functionName}"
                                dir("lambda/${functionName}") {
                                    if (isFargate(functionName)) {
                                        echo "Deploying Fargate to QA for ${functionName} with image ${getImageName(functionName)}"
                                        fargateDeploy environment: 'qa',
                                            awsRegions: AWS_REGIONS,
                                            gitCommit: env.GIT_COMMIT,
                                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                            awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                            awsDeploymentRoleName: QA_DEPLOYMENT_ROLE,
                                            serviceName: "fargate-nr-owndel-${functionName}",
                                            clusterName: "qa-fargate-nr-owndel-${functionName}",
                                            forceScaleOut: true,
                                            verifyMode: 'TASK_RUNNING',
                                            deployType: 'CREATE_TASK_DEFINITION',
                                            imageUri: "${ECR_ACCOUNT_ID}.dkr.ecr.${AWS_REGIONS[0]}.amazonaws.com/${getImageName(functionName)}:${env.GIT_COMMIT}"
                                    } else {
                                        lambdaDeploy environment: 'qa',
                                            awsRegions: AWS_REGIONS,
                                            imageTag: env.GIT_COMMIT,
                                            imageName: getImageName(functionName),
                                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                            awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                            awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Deploying to PROD for ${functionName}"
                                dir("lambda/${functionName}") {
                                    if (isFargate(functionName)) {
                                        echo "Deploying Fargate to PROD for ${functionName} with image ${getImageName(functionName)}"
                                        fargateDeploy environment: 'prod',
                                            awsRegions: AWS_REGIONS,
                                            gitCommit: env.GIT_COMMIT,
                                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                            awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                            awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE,
                                            serviceName: "fargate-nr-owndel-${functionName}",
                                            clusterName: "prod-fargate-nr-owndel-${functionName}",
                                            forceScaleOut: true,
                                            verifyMode: 'TASK_RUNNING',
                                            deployType: 'CREATE_TASK_DEFINITION',
                                            imageUri: "${ECR_ACCOUNT_ID}.dkr.ecr.${AWS_REGIONS[0]}.amazonaws.com/${getImageName(functionName)}:${env.GIT_COMMIT}"
                                    } else {
                                        lambdaDeploy environment: 'prod',
                                            awsRegions: AWS_REGIONS,
                                            imageTag: env.GIT_COMMIT,
                                            imageName: getImageName(functionName),
                                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                            awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                            awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                                    }
                                }
                                datadogSoftwareCatalogPublish(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }
     }

    post {
        regression {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
    }
}

def getFunctionsToBuild() {
    if (this.@functionsToBuild != null) {
        return this.@functionsToBuild
    }

    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

    if (lambdaFunctionName) {
        this.@functionsToBuild = [lambdaFunctionName]
    } else {
        def lambdaDirectories = findFiles(glob: '**/Dockerfile')
        this.@functionsToBuild = getModifiedFunctions branchName: env.BRANCH_NAME,
            previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
            lambdaDirectories: lambdaDirectories
    }

    if (this.@functionsToBuild) {
        currentBuild.description = this.@functionsToBuild.join('<br>')
    }

    return this.@functionsToBuild
}
