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

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2019-10790',
    'CVE-2025-64756',
    'CVE-2024-21538',
    'CVE-2025-22868', // Can be removed when a fixed version of the Datadog extension is released https://github.com/DataDog/datadog-lambda-extension/issues/586
    'CVE-2025-22871',
    'CVE-2025-47907',
    'CVE-2025-65945',
    'CVE-2026-23745', // lambda/nodejs base image issue
    'CVE-2026-24842', // lambda/nodejs base image issue
    'CVE-2026-23950', // lambda/nodejs base image issue
    'CVE-2026-25896',
    'CVE-2025-69873',
    'CVE-2026-24001',
    'CVE-2026-2673',   // openssl OS-level RPM, not fixable via npm
    'CVE-2026-26960',  // tar@6.2.1 bundled in npm within Docker image, not a direct dependency
    'CVE-2026-29786',  // tar@6.2.1 bundled in npm within Docker image, not a direct dependency
    'CVE-2026-31802',  // tar@6.2.1 bundled in npm within Docker image, not a direct dependency
    'CVE-2026-27903',  // minimatch@10.2.2 bundled in npm within Docker image, not a direct dependency
    'CVE-2026-27904',  // minimatch@10.2.2 bundled in npm within Docker image, not a direct dependency
    'CVE-2026-33671',   // picomatch@4.0.3 bundled in npm within Docker image, not a direct dependency
    'CVE-2026-27135'    // pkg:deb/debian/nghttp2@1.52.0-1%2Bdeb12u2?arch=amd64&distro=bookworm&epoch=0
]

def lambdaEcrNames = [
    'agreement-tracker': 'agree-tracker',
    'composition-tracker': 'comp-tracker',
    'writer-publisher-tracker': 'wp-tracker',
    'state-recorder': 'state-recorder',
    'report-populator': 'report-populator',
    'row-builder': 'row-builder',
    'report-compiler': 'report-compiler'
]

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: '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}"
                                def functionPath = "lambda"
                                if (!lambdaEcrNames.containsKey(functionName)) {
                                    functionPath = "scripts"
                                }

                                dir("${functionPath}/${functionName}") {
                                    complianceChecks()
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Validate Software Catalog Definition') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                if(lambdaEcrNames.containsKey(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}"
                                if (lambdaEcrNames.containsKey(functionName)) {
                                    dir("lambda/${functionName}") {
                                        sh "docker compose run --rm --build lint-and-test"
                                    }
                                } else {
                                    dir("scripts/${functionName}") {
                                        yarnRun(scriptNames: [
                                            'test'
                                        ],
                                        envVars: ['NODE_OPTIONS': '--max_old_space_size=4096'])
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Static App Security Tests for ${functionName}"
                                def functionPath = "lambda"
                                if (!lambdaEcrNames.containsKey(functionName)) {
                                    functionPath = "scripts"
                                }
                                sastTests(projectDir: "${functionPath}/${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): {
                                if(lambdaEcrNames.containsKey(functionName)){
                                    withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')]) {
                                        echo "Building for ${functionName}"
                                        dockerToEcr awsRegions: AWS_REGIONS,
                                            ecrAccountId: ECR_ACCOUNT_ID,
                                            imageName: "lambda-publishing-changelog-${lambdaEcrNames[functionName]}",
                                            imageTag: env.GIT_COMMIT,
                                            dockerBuildContext: "lambda/${functionName}",
                                            dockerBuildSecrets: [[id: 'tokens', 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): {
                                if(lambdaEcrNames.containsKey(functionName)){
                                    echo "Scanning Docker Images for ${functionName}"
                                    dir("lambda/${functionName}") {
                                        dockerScan awsRegion: AWS_REGIONS[0],
                                            ecrAccountId: ECR_ACCOUNT_ID,
                                            imageName: "lambda-publishing-changelog-${lambdaEcrNames[functionName]}",
                                            imageTag: env.GIT_COMMIT,
                                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                if(lambdaEcrNames.containsKey(functionName)){
                                    echo "Deploying to QA for ${functionName}"
                                    dir("lambda/${functionName}") {
                                        lambdaDeploy environment: 'qa',
                                            awsRegions: AWS_REGIONS,
                                            imageTag: env.GIT_COMMIT,
                                            imageName: "lambda-publishing-changelog-${lambdaEcrNames[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): {
                                if(lambdaEcrNames.containsKey(functionName)){
                                    echo "Deploying to PROD for ${functionName}"
                                    dir("lambda/${functionName}") {
                                        lambdaDeploy environment: 'prod',
                                            awsRegions: AWS_REGIONS,
                                            imageTag: env.GIT_COMMIT,
                                            imageName: "lambda-publishing-changelog-${lambdaEcrNames[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
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}

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')
        def scriptDirs = findFiles(glob: 'scripts/**/Jenkinsfile')

        this.@functionsToBuild = getModifiedFunctions branchName: env.BRANCH_NAME,
            previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
            lambdaDirectories: lambdaDirectories
        this.@functionsToBuild += getModifiedScripts branchName: env.BRANCH_NAME,
            previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
            scriptDirs: scriptDirs
    }

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

    return this.@functionsToBuild
}

def getModifiedScripts(Map args) {
    def modifiedScripts = []

    def branchName = args.branchName
    def previousSuccessfulCommit = args.previousSuccessfulCommit

    def directories = args.scriptDirs.collect{ it.path.replaceAll('/Jenkinsfile$', '') }
    def modifiedDirectories = getModifiedPaths(
        branchName: branchName,
        previousSuccessfulCommit: previousSuccessfulCommit,
        paths: directories
    )
    modifiedScripts = modifiedDirectories.collect { it.tokenize('/').last() }
    return modifiedScripts
}
