def APP_NAME = 'frontend-audio-player'
def SLACK_NOTIFY_CHANNEL = '#streaming-player'
def DEFAULT_AWS_REGION = 'us-east-1'

def QA_CDN_S3_PATH = "qa-orcd-cdn/${APP_NAME}"
def PROD_CDN_S3_PATH = "prod-orcd-cdn/${APP_NAME}"

pipeline {
    agent {
        label 'aws'
    }

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        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.')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*|.*deploy pri.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            when {
                not {
                    environment name: 'GITHUB_COMMENT', value: 'deploy pri'
                }
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                ]) {
                    yarnRun([
                        scriptNames: ['test'],
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}"
                        ]
                    ])
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${APP_NAME}"
                    sonarScan project: APP_NAME, language: 'js'
                }
            }
        }
        stage('QA CDN Deploy') {
            when {
                branch 'master'
            }
            steps {
                script {
                    // Build
                    withCredentials([
                        string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                    ]) {
                        yarnRun ([
                            scriptNames: ['deploy'],
                            envVars: [
                                PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                                ENV: 'qa',
                                GIT_COMMIT: env.GIT_COMMIT,
                                APPLICATION_NAME: 'audio-player',
                            ]
                        ])
                    }

                    // Publish
                    withAWS(region: DEFAULT_AWS_REGION, credentials: 'cdn-deploy') {
                        step([$class: 'hudson.plugins.s3.S3BucketPublisher',
                            entries: [
                                [
                                    bucket: "${QA_CDN_S3_PATH}/${env.GIT_COMMIT}",
                                    sourceFile: 'build/',
                                    selectedRegion: DEFAULT_AWS_REGION,
                                    flatten: true,
                                    noUploadOnFailure: true,
                                ],
                                [
                                    bucket: QA_CDN_S3_PATH,
                                    sourceFile: 'build/manifest',
                                    selectedRegion: DEFAULT_AWS_REGION,
                                    flatten: true,
                                    noUploadOnFailure: true,
                                ],
                            ]
                        ])
                    }
                }
            }
        }
        stage('QA CDN Cache Invalidation') {
            when {
                branch 'master'
            }
            steps {
                cdnInvalidate(
                    env: 'qa',
                    appName: 'frontend-audio-player'
                )
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            steps {
                playwrightTests(
                    tags: '@frontend_audio_player',
                    slackNotificationChannels: [SLACK_NOTIFY_CHANNEL]
                )
            }
        }
        stage('Prod CDN Deploy') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    // Build
                    withCredentials([
                        string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                    ]) {
                        yarnRun ([
                            scriptNames: ['deploy'],
                            envVars: [
                                PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                                ENV: 'prod',
                                GIT_COMMIT: env.GIT_COMMIT,
                                APPLICATION_NAME: 'audio-player',
                            ]
                        ])
                    }

                    // Deploy to CDN
                    withAWS(region: DEFAULT_AWS_REGION, credentials: 'cdn-deploy') {
                        step([$class: 'hudson.plugins.s3.S3BucketPublisher',
                            entries: [
                                [
                                    bucket: "${PROD_CDN_S3_PATH}/${env.GIT_COMMIT}",
                                    sourceFile: 'build/',
                                    selectedRegion: DEFAULT_AWS_REGION,
                                    flatten: true,
                                    noUploadOnFailure: true,
                                ],
                                [
                                    bucket: PROD_CDN_S3_PATH,
                                    sourceFile: 'build/manifest',
                                    selectedRegion: DEFAULT_AWS_REGION,
                                    flatten: true,
                                    noUploadOnFailure: true,
                                ],
                            ]
                        ])
                    }
                }
            }
        }
        stage('Prod CDN Cache Invalidation') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                cdnInvalidate(
                    env: 'prod',
                    appName: 'frontend-audio-player'
                )
            }
        }
        stage('Publish Package') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    withCredentials([
                        usernamePassword(credentialsId: 'packagecloud_api_credentials', usernameVariable: 'PACKAGECLOUD_USER', passwordVariable: 'PACKAGECLOUD_TOKEN'),
                    ]) {
                        yarnRun ([
                            scriptNames: ['deploy-esm'],
                            envVars: [
                                PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                                ENV: 'prod',
                            ]
                        ])
                    }
                }
            }
        }
        stage('Publish Software Catalog') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }
    }
    post {
        failure {
            cleanWs();

            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFY_CHANNEL
                }
            }
        }
    }
}
