def GITHUB_REPOSITORY = 'songwhip-presaves'
def SLACK_E2E_NOTIFY_CHANNEL = '#cypress-test-e2e-results,#songwhip-alerts'
def SLACK_NOTIFICATION_CHANNEL = "#songwhip-alerts-dev"
def AWS_REGIONS = ['us-east-1']
def ECR_ACCOUNT_ID = '086679231553'
def QA_ACCOUNT_ID = '619719722105'
def PROD_ACCOUNT_ID = '926734670777'
def QA_DEPLOYMENT_ROLE = 'qa-songwhip-jenkins-pipeline-deploy-role'
def PROD_DEPLOYMENT_ROLE = 'prod-songwhip-jenkins-pipeline-deploy-role'

def VULNERABILITIES_TO_IGNORE = []

pipeline {
    agent {
        label 'aws'
    }

    parameters {
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag or Git revision.')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Tests & Analysis') {
            parallel {
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Datadog Software Catalog Validation') {
                    steps {
                        script {
                            datadogSoftwareCatalogValidate()
                        }
                    }
                }
                stage('Format, Lint & Unit Tests') {
                    steps {
                        pnpmRun(scriptNames: ['test'])
                    }
                }
                
                stage('Integration Tests') {
                    steps {
                        withCredentials([
                            string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN')
                        ]) {
                            sh 'scripts/test-integration-ci.sh'
                        }
                    }
                }
            }
        }

        stage('Create Docker Image') {
            when {
                branch 'master'
            }
            steps {
                withCredentials([
                    string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN')
                ]) {
                    dockerToEcr (
                        awsRegions: AWS_REGIONS, 
                        ecrAccountId: ECR_ACCOUNT_ID, 
                        imageName: GITHUB_REPOSITORY,
                        imageTag: env.GIT_COMMIT, 
                        dockerBuildSecrets: [
                            [id: 'GITHUB_NPM_TOKEN', env: 'GITHUB_NPM_TOKEN']
                        ]
                    )
                }
            }
        }

        stage('Scan Docker Image') {
            when {
                branch 'master'
            }
            steps {
                dockerScan (
                    awsRegion: AWS_REGIONS[0], 
                    ecrAccountId: ECR_ACCOUNT_ID, 
                    imageName: GITHUB_REPOSITORY, 
                    imageTag: env.GIT_COMMIT,
                    vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE,
                    failBuild: false,
                    slackNotificationChannel: SLACK_NOTIFICATION_CHANNEL
                )
            }
        }

        stage('Apply QA Schema Migrations') {
            when {
                branch 'master'
            }
            steps {
                withSecrets(
                    awsAccountId: QA_ACCOUNT_ID,
                    awsRole: QA_DEPLOYMENT_ROLE,
                    secrets: [
                        [id: 'qa/songwhip-presaves/PRESAVES_DB_ADMIN_PASSWORD', environmentVariable: 'PRESAVES_DB_PASSWORD']
                    ]
                ) {
                    pnpmRun(
                        scriptNames: ['db:migrate:schema:up:ci'],
                        envVars: [
                            'PRESAVES_DB_HOST': 'qa-songwhip-presaves.cluster-ch72m6xtmre9.us-east-1.rds.amazonaws.com',
                            'PRESAVES_DB_PASSWORD': env.PRESAVES_DB_PASSWORD
                        ]
                    )
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                fargateDeploy (
                    environment: 'qa', 
                    awsRegions: AWS_REGIONS, 
                    gitCommit: env.GIT_COMMIT, 
                    serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, 
                    awsDeploymentTargetAccountId: QA_ACCOUNT_ID, 
                    awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                )
            }
        }

        stage('Apply PROD Schema Migrations') {
            when {
                branch 'master'
            }
            steps {
                withSecrets(
                    awsAccountId: PROD_ACCOUNT_ID,
                    awsRole: PROD_DEPLOYMENT_ROLE,
                    secrets: [
                        [id: 'prod/songwhip-presaves/PRESAVES_DB_ADMIN_PASSWORD', environmentVariable: 'PRESAVES_DB_PASSWORD']
                    ]
                ) {
                    pnpmRun(
                        scriptNames: ['db:migrate:schema:up:ci'],
                        envVars: [
                            'PRESAVES_DB_HOST': 'prod-songwhip-presaves.cluster-cuc7qfpb194c.us-east-1.rds.amazonaws.com',
                            'PRESAVES_DB_PASSWORD': env.PRESAVES_DB_PASSWORD
                        ]
                    )
                }
            }
        }

        stage('Deploy to PROD') {
            when {
                branch 'master'
            }
            steps {
                fargateDeploy (
                    environment: 'prod', 
                    awsRegions: AWS_REGIONS, 
                    gitCommit: env.GIT_COMMIT, 
                    serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, 
                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, 
                    awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                )
            }
        }

        stage('Publish Software Catalog Definition') {
            when {
                branch 'master'
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        failure {
            cleanWs()
        }
    }
}
