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

// Per-lambda vulnerability ignore list
Map<String, List<String>> lambdaVulnerabilityMap = [
    'acknowledge': [
    ],
    'audio_validation': [
    ],
    'encoding_route': [
    ],
    'error_reporting': [
    ],
    'image_encoding': [
    ],
    'image_validation': [
    ],
    'trigger_spatial_transcoding': [
    ],
    'hive_ai_detection': [
    ],
    'hive_text_recognition': [
    ],
    'spatial_audio_validation': [
        // libcurl HIGH CVEs with no Debian fix yet. Drop once curl > 8.14.1-2+deb13u3 ships a patch.
        // https://security-tracker.debian.org/tracker/CVE-2026-6276
        // https://security-tracker.debian.org/tracker/CVE-2026-3805
        'CVE-2026-6276',
        'CVE-2026-3805',
        // libmbedcrypto16 HIGH/CRITICAL CVEs pulled by ffmpeg -> librist4, with no Debian trixie fix.
        // librist is the RIST network protocol; this worker only runs ffmpeg loudnorm on local
        // audio, so the RIST code path is never reached. Drop once trixie ships a fixed mbedtls.
        // https://security-tracker.debian.org/tracker/source-package/mbedtls
        'CVE-2026-34876',
        'CVE-2026-25835',
        'CVE-2026-34874',
        'CVE-2026-34872',
        'CVE-2026-34873',
        'CVE-2026-34875',
    ],
]

// For all new Fargate tasks added, they must be added here along with their deployment type.
// Fargate deployment types: [UPDATE_CLOUDWATCH_EVENT, CREATE_TASK_DEFINITION, UPDATE_SERVICE]
@groovy.transform.Field
tasksToBuild = [
    [taskName: 'spatial_audio_validation', deployType: 'UPDATE_SERVICE'],
]
String DEFAULT_TASK_DEPLOY_TYPE = 'CREATE_TASK_DEFINITION'

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_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).'
        )
        booleanParam(
            name: 'VERIFY_BUILD',
            defaultValue: false,
            description: 'Force build and test step to verify health.'
        )
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
        parameterizedCron(env.BRANCH_NAME == 'master' ? '@weekly %DEPLOY_TO_PROD=false;VERIFY_BUILD=true;LAMBDA_FUNCTION_NAMES=*' : '')
    }

    stages {
        stage('Load Shared Libraries') {
            agent any
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Build Test and Scan') {
            when {
                expression { isPullRequest() || params.VERIFY_BUILD }
            }
            parallel {
                stage('Sonar Scan and Analysis') {
                    agent any
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Running Sonar scan for ${functionName}"
                            sonarScan(
                                project: "${GITHUB_REPOSITORY}-${functionName.replaceAll('_', '-')}",
                                language: 'py',
                                projectBaseDir: "lambda/${functionName}",
                                qualityGateTimeout: 300,
                                exclusions: 'dev/**,fargate/**,tests/**,dockerToEcr/**,dockerScan/**,fargateDeploy/**,lambdaDeploy/**,src/vendor/**'
                            )
                        }
                    }
                }
                stage('Compliance Checks') {
                    agent any
                    steps {
                        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 ->
                            script {
                                echo "Running Unit Tests and Style Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    withEcr {
                                        withEnv(["COMPOSE_PROJECT_NAME=${env.BUILD_TAG.toLowerCase()}-${functionName}"]) {
                                            try {
                                                sh """
                                                    mkdir -p build
                                                    chmod a+w build
                                                    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('Create and Docker Scan a Release') {
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            script {
                                def sanitizedFunctionName = sanitizeFunctionName(functionName)
                                def imageName = "${GITHUB_REPOSITORY}-${sanitizedFunctionName}"
                                echo "Building for ${functionName}"
                                dockerToEcr(
                                    awsRegions: AWS_REGIONS,
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: imageName,
                                    imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                                    dockerBuildContext: "lambda/${functionName}",
                                    dockerBuildFile: "lambda/${functionName}/Dockerfile"
                                )
                                dockerScan(
                                    awsRegion: AWS_REGIONS[0],
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: imageName,
                                    imageTag: isPullRequest() ? env.BRANCH_NAME : "VERIFY-BUILD-${env.BUILD_NUMBER}",
                                    vulnerabilitiesToIgnore: lambdaVulnerabilityMap[functionName]
                                )
                            }
                        }
                    }
                }
            }
        }
        stage('Retag and Docker Scan a Release') {
            when {
                expression { !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        def sanitizedFunctionName = sanitizeFunctionName(functionName)
                        def imageName = "${GITHUB_REPOSITORY}-${sanitizedFunctionName}"
                        def commitHash = getCommitHash(functionName)
                        def prNumber = githubGetCommitPrs(
                            repo: GITHUB_REPOSITORY,
                            commitSha: commitHash
                        )[0].number
                        retagEcrImage(
                            awsRegions: AWS_REGIONS,
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: imageName,
                            imageTag: 'PR-' + prNumber,
                            newTag: commitHash
                        )
                        dockerScan(
                            awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: imageName,
                            imageTag: commitHash,
                            vulnerabilitiesToIgnore: lambdaVulnerabilityMap[functionName]
                        )
                    }
                }
            }
        }
        stage('Deploy to QA') {
            when {
                expression { !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        def sanitizedFunctionName = sanitizeFunctionName(functionName)
                        def imageName = "${GITHUB_REPOSITORY}-${sanitizedFunctionName}"
                        def commitHash = getCommitHash(functionName)
                        echo "Deploying to QA for ${functionName}"
                        if (isTaskDir(functionName)) {
                            def deployType = getTaskDeployType(functionName)
                            dir("lambda/${functionName}") {
                                fargateDeploy(
                                    environment: 'qa',
                                    awsRegions: AWS_REGIONS,
                                    gitCommit: commitHash,
                                    serviceName: imageName,
                                    deployType: deployType,
                                    imageNameOverride: imageName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                    awsDeploymentRoleName: QA_DEPLOYMENT_ROLE,
                                    verifyMode: 'OFF',
                                    updateTimeout: 600,
                                    forceScaleOut: true
                                )
                            }
                        } else {
                            dir("lambda/${functionName}") {
                                lambdaDeploy(
                                    environment: 'qa',
                                    awsRegions: AWS_REGIONS,
                                    imageTag: commitHash,
                                    imageName: imageName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                                    awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                                )
                            }
                        }
                    }
                }
            }
        }
        stage('E2E Tests') {
            agent any
            when {
                expression { !isPullRequest() }
            }
            steps {
                playwrightTests tags: '@ows_assets'
            }
        }
        stage('Deploy to PROD') {
            when {
                expression { params.DEPLOY_TO_PROD && !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        def sanitizedFunctionName = sanitizeFunctionName(functionName)
                        def imageName = "${GITHUB_REPOSITORY}-${sanitizedFunctionName}"
                        def commitHash = getCommitHash(functionName)
                        echo "Deploying to PROD for ${functionName}"
                        if (isTaskDir(functionName)) {
                            def deployType = getTaskDeployType(functionName)
                            dir("lambda/${functionName}") {
                                fargateDeploy(
                                    environment: 'prod',
                                    awsRegions: AWS_REGIONS,
                                    gitCommit: commitHash,
                                    serviceName: imageName,
                                    deployType: deployType,
                                    imageNameOverride: imageName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                    awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE,
                                    verifyMode: 'OFF',
                                    updateTimeout: 600,
                                    forceScaleOut: true
                                )
                            }
                        } else {
                            dir("lambda/${functionName}") {
                                lambdaDeploy(
                                    environment: 'prod',
                                    awsRegions: AWS_REGIONS,
                                    imageTag: commitHash,
                                    imageName: imageName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                    awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                                )
                            }
                        }
                    }
                }
            }
        }
        stage('Publish Software Catalog Definition') {
            when {
                expression { params.DEPLOY_TO_PROD && !isPullRequest() }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Publishing Software Catalog definition for ${functionName}"
                    datadogSoftwareCatalogPublish(servicePath: "lambda/${functionName}")
                }
            }
        }
    }
    post {
        regression {
            script {
                if (!isPullRequest()) {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (!isPullRequest()) {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
    }
}

def isPullRequest() {
    return env.BRANCH_NAME != 'master'
}

def getCommitHash(String functionName) {
    return sh(
        script: "git log -1 --pretty=format:'%H' -- lambda/${functionName}",
        returnStdout: true
    ).trim()
}

def sanitizeFunctionName(String functionName) {
    return functionName.replaceAll('_', '-')
}

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',
        projectsToBuild: params.LAMBDA_FUNCTION_NAMES ? params.LAMBDA_FUNCTION_NAMES.split(',') as Set : null
    )
}

def isTaskDir(String functionName) {
    for (task in this.@tasksToBuild) {
        if (task.taskName == functionName) {
            return true
        }
    }
    return false
}

def getTaskDeployType(String taskName) {
    for (task in this.@tasksToBuild) {
        if (task.taskName == taskName) {
            return task.deployType
        }
    }
    return DEFAULT_TASK_DEPLOY_TYPE
}
