String GITHUB_REPOSITORY = 'lambda-nr-ownership-ingest'
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

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2024-21538',
    'CV-2024-24784', // datadog-agent
    'CVE-224-24790', // datadog-agent
    'CVE-2019-10790', // kafkajs - taffydb
    'CVE-2025-57319',
    'CVE-2025-64756', // glob in lambda runtime layer
    'CVE-2025-61729', // libcap in lambda runtime
    'CVE-2025-14087', // glib2 in lambda runtime
    'CVE-2025-13601', // glib2 in lambda runtime
    'CVE-2025-9086', // libcurl-minimal in lambda runtime
    'CVE-2026-23950', // tar issue
    'CVE-2026-23745', // tar issue
    "CVE-2025-15467",
    "CVE-2025-13151",
    'CVE-2026-25547',
    'CVE-2026-25896',
    'CVE-2026-24001',
    'CVE-2026-24842',
    'CVE-2026-26278',
    'CVE-2026-26960',
    'CVE-2026-26996',
    'CVE-2026-31802',
    'CVE-2026-25679',
    'CVE-2026-27142',
    'CVE-2026-29786',
    'CVE-2026-27903',
    'CVE-2026-27904',
    'CVE-2026-27942',
    'CVE-2025-69873', // ajv@7.2.4
    'CVE-2026-2673', // openssl-snapsafe-libs@3.2.2-1
    'CVE-2026-33671', // picomatch@4.0.3
    'CVE-2026-33036', // fast-xml-parser@4.4.1
    'CVE-2026-25128', // fast-xml-parser@5.2.5
    'CVE-2026-42043', // axios
    'CVE-2026-42044', // axios
    'CVE-2026-33750', // brace-expansion
    'CVE-2026-4046', // rpm glibc
    'CVE-2026-4800', // lodash
    'CVE-2026-41242', // protobufjs
    'CVE-2025-13465', // lodash
    'CVE-2026-42033', // axios
    'CVE-2026-42035', // axios
    'CVE-2026-42038', // axios
    'CVE-2026-42039', // axios
    'CVE-2026-42264', // axios
    'CVE-2026-44289', // protobufjs
    'CVE-2026-44290', // protobufjs
    'CVE-2026-44291', // protobufjs
    'CVE-2026-44293', // protobufjs
    'CVE-2026-44665', // fast-xml-builder
    'CVE-2026-6321', // fast-uri
    'CVE-2026-6322', // fast-uri
    'CVE-2026-3805', //
    'CVE-2026-41907', // uuid@9.0.1 in built image
    'CVE-2026-4926',
    'CVE-2026-45149', // brace-expansion in global npm (lambda base image)
    'CVE-2026-48864', // libsolv rpm in lambda base image
    'CVE-2026-34182', // openssl-snapsafe-libs rpm in lambda base image (CRITICAL, blocking)
    'CVE-2026-34180', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-34181', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-34183', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-42764', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-42768', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-45445', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-45447', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-7383', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-9076', // openssl-snapsafe-libs rpm in lambda base image
    'CVE-2026-12151', // undici in global npm (lambda base image)
    'CVE-2026-48779', // ws in @aws-sdk (lambda runtime)
    'CVE-2026-12143', // form-data in @aws-sdk (lambda runtime)
    'CVE-2026-44486', // axios in @aws-sdk (lambda runtime)
    'CVE-2026-44487', // axios in @aws-sdk (lambda runtime)
    'CVE-2026-44488', // axios in @aws-sdk (lambda runtime)
    'CVE-2026-44490', // axios in @aws-sdk (lambda runtime)
    'CVE-2026-44492', // axios in @aws-sdk (lambda runtime)
    'CVE-2026-44494', // axios in @aws-sdk (lambda runtime)
    'CVE-2026-44496', // axios in @aws-sdk (lambda runtime)

]

pipeline {
    agent none

    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('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Compliance Checks') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Compliance Checks for ${functionName}"
                    dir("lambda/${functionName}") {
                        complianceChecks()
                    }
                }
            }
        }

        stage('Validate Software Catalog Definition') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                echo "Validating Software Catalog definition for ${functionName}"
                    datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                }
            }
        }

        stage('Unit Tests and Style Checks') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')]){
                        script {
                            echo "Running Unit Tests and Style Checks for ${functionName}"
                            dir("lambda/${functionName}") {
                                try {
                                    sh "docker compose run --rm --build lint-and-test"
                                }
                                finally {
                                    sh "docker compose down -v"
                                }
                            }
                        }
                    }
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Static App Security Tests for ${functionName}"
                    sastTests(projectDir: "lambda/${functionName}")
                }
            }
        }

        stage('Sonar Scan and Analysis') {
            agent any
            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' }
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Building for ${functionName}"
                    withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')]) {
                        dockerToEcr awsRegions: AWS_REGIONS,
                        ecrAccountId: ECR_ACCOUNT_ID,
                        imageName: "lambda-nr-ownership-ingest-${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' }
                    expression { pullRequest.labels.contains('build docker') }
                }
            }
            steps {
                withModifiedFunctions { functionName ->
                    echo "Scanning Docker Images for ${functionName}"
                    dir("lambda/${functionName}") {
                        dockerScan awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: "lambda-nr-ownership-ingest-${functionName}",
                            imageTag: env.GIT_COMMIT,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                    }
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                withModifiedFunctions { functionName ->
                    echo "Deploying to QA for ${functionName}"
                    dir("lambda/${functionName}") {
                        lambdaDeploy environment: 'qa',
                            awsRegions: AWS_REGIONS,
                            imageTag: env.GIT_COMMIT,
                            imageName: "lambda-nr-ownership-ingest-${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 {
                withModifiedFunctions { functionName ->
                    echo "Deploying to PROD for ${functionName}"
                    dir("lambda/${functionName}") {
                        lambdaDeploy environment: 'prod',
                            awsRegions: AWS_REGIONS,
                            imageTag: env.GIT_COMMIT,
                            imageName: "lambda-nr-ownership-ingest-${functionName}",
                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                            awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                            awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                    }
                }
            }
        }

        stage('Publish Software Catalog Definition') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    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 {
        node {
            def scmVars = checkout scm
            def lambdaDirectories = findFiles(glob: '**/Dockerfile')
            this.@functionsToBuild = getModifiedFunctions branchName: scmVars.BRANCH_NAME,
                previousSuccessfulCommit: scmVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
                lambdaDirectories: lambdaDirectories
        }
    }

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

    return this.@functionsToBuild
}

def withModifiedFunctions(Map args = [:], Closure steps) {
    parallel(getFunctionsToBuild().collectEntries { functionName ->
        return [
            (functionName): {
                node {
                    if (args.checkout?.toBoolean()) {
                        cleanWs()
                        def scmVars = checkout scm
                        // Set SCM vars as environment variables to replicate default checkout functionality
                        scmVars.each { k, v ->
                            env."${k}" = v
                        }
                    }
                    steps(functionName)
                }
            }
        ]
    })
}
