String GITHUB_REPOSITORY = 'lambda-{{ cookiecutter.repo_name }}'
String ECR_ACCOUNT_ID = '{{ cookiecutter.ecr_account_id }}'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '{{ cookiecutter.slack_notifications_channel }}'
String QA_ACCOUNT_ID = '{{ cookiecutter.qa_account_id }}'
String QA_DEPLOYMENT_ROLE = '{{ cookiecutter.qa_deployment_role }}'
String PROD_ACCOUNT_ID = '{{ cookiecutter.prod_account_id }}'
String PROD_DEPLOYMENT_ROLE = '{{ cookiecutter.prod_deployment_role }}'

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).')
    }

    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('Build Test and Scan') {
            parallel {
                stage('Validate Software Catalog Definition') {
                    steps {
                        withModifiedFunctions(checkout: true) { 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}") {
                                    withEnv(["COMPOSE_PROJECT_NAME=${env.BUILD_TAG.toLowerCase()}-${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: 'py', exclusions: 'lambda/**/tests/**'
                        }
                    }
                }

                stage('Create and Scan a Release') {
                    steps {
                        withModifiedFunctions(checkout: true) { functionName ->
                            echo "Building for ${functionName}"
                            dockerToEcr awsRegions: AWS_REGIONS,
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: "lambda-${functionName.replaceAll('_', '-')}",
                                imageTag: env.GIT_COMMIT,
                                dockerBuildContext: "lambda/${functionName}",
                                dockerBuildFile: "lambda/${functionName}/Dockerfile"
                            echo "Scanning Docker Images for ${functionName}"
                            dockerScan awsRegion: AWS_REGIONS[0],
                                ecrAccountId: ECR_ACCOUNT_ID,
                                imageName: "lambda-${functionName.replaceAll('_', '-')}",
                                imageTag: env.GIT_COMMIT,
                                slackNotificationChannel: (env.BRANCH_NAME == 'master' ? SLACK_NOTIFICATIONS_CHANNEL : null)
                        }
                    }
                }
            }
        }

        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-${functionName.replaceAll('_', '-')}",
                            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(checkout: true) { functionName ->
                    echo "Deploying to PROD for ${functionName}"
                    dir("lambda/${functionName}") {
                        lambdaDeploy environment: 'prod',
                            awsRegions: AWS_REGIONS,
                            imageTag: env.GIT_COMMIT,
                            imageName: "lambda-${functionName.replaceAll('_', '-')}",
                            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
                }
            }
        }
    }
}

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(',') : null
    )
}
