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

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2024-45338', // dependency in the datadog-agent extension
    'CVE-2024-34156', // dependency in the datadog-agent extension
    'CVE-2023-32643', // dependency in the base image
    'CVE-2023-29499', // dependency in base image
    'CVE-2023-32636', // dependency in base image
    'CVE-2025-22868', // golang cve
    'CVE-2024-34158', // stack exhaustion in go, in base image
    'CVE-2025-22871', // Vulnerability in cryptography-related dependency; no immediate impact on current usage
    'CVE-2025-27363', // Vulnerability in HTTP library; mitigated by internal usage patterns
    'CVE-2007-4559',  // Long-standing Python tarfile vulnerability; usage is controlled and safe in this context
    'CVE-2025-24928', // Vulnerability in database-related library; no immediate impact on current usage
    'CVE-2025-27113', // Vulnerability in YAML parsing library; mitigated by controlled input
    'CVE-2022-49043', // Vulnerability in protobuf library; no immediate impact on current usage
    'CVE-2024-56171', // Vulnerability in Elasticsearch library; mitigated by internal usage patterns
    'CVE-2024-7592',  // Vulnerability in CFFI library; no immediate impact on current usage
    'CVE-2025-1390',  // Vulnerability in JWT library; mitigated by controlled input and usage
    'CVE-2025-47907',
    'CVE-2025-32414', // libxml2 vulnerability in the base image
    'CVE-2025-32415', // libxml2 vulnerability in the base image
    'CVE-2025-49794', // libxml2 vulnerability in the base image
    'CVE-2025-49796', // libxml2 vulnerability in the base image
    'CVE-2025-6021',  // libxml2 vulnerability in the base image
    'CVE-2025-7425',  // libxslt vulnerability in the base image
    'CVE-2025-6965',  // SQLite memory corruption
    'CVE-2025-8194',  // CPython version in Amazon base image
    'CVE-2025-5222',  // buffer overflow in genrb
    'CVE-2025-58188', // aws-lambda-rie vulnerability in the base image
    'CVE-2025-61725', // aws-lambda-rie vulnerability in the base image
    'CVE-2025-61723', // aws-lambda-rie vulnerability in the base image
    'CVE-2025-58187', // aws-lambda-rie vulnerability in the base image
    'CVE-2025-9086',  // pkg:rpm/amazon/libcurl@8.3.0-1.amzn2.0.7
    'CVE-2025-13601', // base image issue: pkg:rpm/amazon/glib2@2.74.7-689.amzn2023.0.2
    'CVE-2025-61729', // affects aws-lambda-rie and datadog-agent-go binaries
    'CVE-2025-66418', // urllib3
    'CVE-2025-66471', // urllib3
    'CVE-2025-64720', // pkg:rpm/amazon/libpng@1.5.13-8.amzn2.0.5
    'CVE-2025-14087', // pkg:rpm/amazon/glib2@2.56.1-9.amzn2.0.8
    'CVE-2026-21441', // urllib3
    'CVE-2025-68973', // gnu vulnerability
    'CVE-2026-23949', // pkg:pypi/jaraco.context@5.3.0  base image issue
    'CVE-2025-61726', // aws-lambda-rie
    'CVE-2025-13151', // pkg:rpm/amazon/libtasn1@4.10-1.amzn2.0.6
    'CVE-2025-24528', // pkg:rpm/amazon/krb5-libs@1.15.1-55.amzn2.2.8
    'CVE-2025-4565',  // pkg:pypi/protobuf@5.27.1
    'CVE-2026-0994',  // pkg:pypi/protobuf@5.27.1
    'CVE-2026-24049', // remove once all services on wheel 0.46.2,
    'CVE-2025-68121', // base image issue,
    'CVE-2026-24051', // base image issue
    'CVE-2026-25679',  // go_toolchain 1.25.7
    'CVE-2026-33186',  // pkg:golang/google.golang.org/grpc@v1.66.0
    'CVE-2026-32874',  // pkg:pypi/ujson@5.11.0
    'CVE-2026-32875',  // pkg:pypi/ujson@5.11.0
    'CVE-2026-32597',  // pkg:pypi/PyJWT@2.11.0
    'CVE-2026-25210',  // pkg:rpm/amazon/expat@2.1.0-15.amzn2.0.4
    'CVE-2026-25646',  // pkg:rpm/amazon/libpng@1.5.13-8.amzn2.0.5
    'CVE-2026-27135',  // pkg:rpm/amazon/libnghttp2@1.41.0-1.amzn2.0.5?arch=x86_64&distro=2&epoch=0&source=nghttp2-1.41.0-1.amzn2.0.5.src.rpm
    'CVE-2026-32280',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-32281',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-32283',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-33416',  // pkg:rpm/amazon/libpng@1.5.13-8.amzn2.0.5?arch=x86_64&distro=2&epoch=2&source=libpng-1.5.13-8.amzn2.0.5.src.rpm
    'CVE-2026-39883',  // pkg:golang/go.opentelemetry.io/otel/sdk@v1.27.0
    'CVE-2026-4519',   // pkg:rpm/amazon/python-libs@2.7.18-1.amzn2.0.9?arch=x86_64&distro=2&epoch=0&source=python-2.7.18-1.amzn2.0.9.src.rpm
    'CVE-2026-6100',   // pkg:rpm/amazon/python-libs@2.7.18-1.amzn2.0.9?arch=x86_64&distro=2&epoch=0&source=python-2.7.18-1.amzn2.0.9.src.rpm
    'CVE-2026-4786',   // pkg:rpm/amazon/python-libs@2.7.18-1.amzn2.0.9?arch=x86_64&distro=2&epoch=0&source=python-2.7.18-1.amzn2.0.9.src.rpm
    'CVE-2025-45768',  // pkg:pypi/PyJWT@2.13.0
    'CVE-2026-33811',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-33814',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-39820',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-39836',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-42499',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
    'CVE-2026-42504',  // pkg:generic/aws-lambda-rie?go_toolchain=1.26.3
    'CVE-2026-39821',  // pkg:golang/golang.org/x/net@v0.29.0
    'CVE-2026-39892',  // pkg:pypi/cryptography@46.0.5
    'CVE-2026-44431',  // pkg:pypi/urllib3@2.6.3
    'CVE-2026-44432',  // pkg:pypi/urllib3@2.6.3
    'CVE-2026-44660',  // pkg:pypi/ujson@5.11.0
    'CVE-2026-27145',  // pkg:generic/aws-lambda-rie?go_toolchain=1.22.7
]

LAMBDA_ALIAS_MAP = [
    'review-queue-populate': 'provisioned',
    'review-notifications': 'provisioned'
]
SKIP_PROD = []

pipeline {
    agent none

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        string(name: 'LAMBDA_FUNCTION_NAMES', defaultValue: '', description: 'Comma-separated list of Lambda function directory names 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 Definitions') {
            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 ->
                    echo "Running Unit Tests and Style Checks for ${functionName}"
                    dir("lambda/${functionName}") {
                        withEcr {
                            script {
                                try {
                                    sh "touch .env && docker compose run --rm --build lint-and-test"
                                }
                                finally {
                                    sh "make ci_unit_lint_clean"
                                }
                            }
                        }
                    }
                }
            }
        }

        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: 'py'
                }
            }
        }

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                withModifiedFunctions { functionName ->
                    echo "Building for ${functionName}"
                    dockerToEcr awsRegions: AWS_REGIONS,
                        ecrAccountId: ECR_ACCOUNT_ID,
                        imageName: "lambda-content-${functionName.replaceAll('_', '-')}",
                        imageTag: env.GIT_COMMIT,
                        dockerBuildContext: "lambda/${functionName}",
                        dockerBuildFile: "lambda/${functionName}/Dockerfile"
                }
            }
        }

        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-content-${functionName.replaceAll('_', '-')}",
                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                            awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                            awsDeploymentRoleName: QA_DEPLOYMENT_ROLE,
                            aliasName: LAMBDA_ALIAS_MAP.get(functionName),
                            publishVersion: LAMBDA_ALIAS_MAP.get(functionName) as Boolean
                    }
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ '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-content-${functionName.replaceAll('_', '-')}",
                            imageTag: env.GIT_COMMIT,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                    }
                }
            }
        }

        stage('E2E Tests') {
            agent any
            when {
                branch 'master'
            }
            steps {
                playwrightTests(tags: '@content_review', reportSuffix: 'contentReview', slackNotificationChannels: ['#content-review-team'])
            }
        }

        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    withModifiedFunctions(checkout: true) { functionName ->
                        if (SKIP_PROD.contains(functionName)) {
                            echo "Not deploying service ${functionName} to PROD as this is explicitly disabled."
                        } else {
                            echo "Deploying to PROD for ${functionName}"
                            dir("lambda/${functionName}") {
                                lambdaDeploy environment: 'prod',
                                    awsRegions: AWS_REGIONS,
                                    imageTag: env.GIT_COMMIT,
                                    imageName: "lambda-content-${functionName.replaceAll('_', '-')}",
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                    awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE,
                                    aliasName: LAMBDA_ALIAS_MAP.get(functionName),
                                    publishVersion: LAMBDA_ALIAS_MAP.get(functionName) as Boolean
                            }
                        }
                        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 withModifiedFunctions(Map args = [:], Closure steps) {
    getMonorepoUtils().withModifiedProjects(args, steps)
}

def getMonorepoUtils() {
    return library("jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}").com.sonymusic.MonorepoUtils.getInstance(
        steps: this,
        projectBasePath: 'lambda',
        excludedProjects: ['example'],
        projectsToBuild: params.LAMBDA_FUNCTION_NAMES ? params.LAMBDA_FUNCTION_NAMES.split(',') : null
    )
}
