String GITHUB_REPOSITORY = 'content-integrations-scripts'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = 'content-review-team'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2025-68973',
    'CVE-2026-21441' // pkg:pypi/urllib3@2.6.2  
]

def modifiedFunctionList = []

pipeline {
    agent any

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

    parameters {
        string(name: 'SCRIPT_NAME', defaultValue: '', description: 'Name of the script 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('Find Modified Functions') {
            steps {
                script {
                    def scriptName = params.SCRIPT_NAME ?: null

                    if (scriptName) {
                        modifiedFunctionList = [scriptName]
                    } else {
                        def scriptDirectories = findFiles(glob: '**/Dockerfile')
                        modifiedFunctionList = getModifiedFunctions branchName: env.BRANCH_NAME,
                                                   previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
                                                   lambdaDirectories: scriptDirectories
                    }
                    if (modifiedFunctionList) {
                        currentBuild.description = modifiedFunctionList.join('<br>')
                    }
                }
            }
        }

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

        stage('Unit Tests and Style Checks') {
            steps {
                script {
                    withEcr {
                        parallel(modifiedFunctionList.collectEntries { functionName ->
                            return [
                                (functionName): {
                                    echo "Running Unit Tests and Style Checks for ${functionName}"
                                    dir("${functionName}") {
                                        sh "make ci_unit_lint_clean"
                                    }
                                }
                            ]
                        })
                    }
                }
            }
        }

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

        stage('Sonar Scan and Analysis') {
            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 {
                script {
                    parallel(modifiedFunctionList.collectEntries { functionName ->
                        return [
                            (functionName): {
                                if (functionName == 'example') {
                                    echo "Skipping build for excluded script"
                                } else {
                                    echo "Building for ${functionName}"
                                    dockerToEcr awsRegions: AWS_REGIONS,
                                        ecrAccountId: ECR_ACCOUNT_ID,
                                        imageName: "content-integrations-${functionName.replaceAll('_', '-')}",
                                        imageTag: env.GIT_COMMIT,
                                        dockerBuildContext: "${functionName}",
                                        dockerBuildFile: "${functionName}/Dockerfile",
                                        dockerBuildTarget: "deploy"
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(modifiedFunctionList.collectEntries { functionName ->
                        return [
                            (functionName): {
                                if (functionName == 'example') {
                                    echo "Skipping scan for excluded script"
                                } else {
                                    echo "Scanning Docker Images for ${functionName}"
                                    dir("${functionName}") {
                                        dockerScan awsRegion: AWS_REGIONS[0],
                                            ecrAccountId: ECR_ACCOUNT_ID,
                                            imageName: "content-integrations-${functionName.replaceAll('_', '-')}",
                                            imageTag: env.GIT_COMMIT,
                                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }
    }

    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()
        }
    }
}
