pipeline {
    agent {
        label 'linux'
    }
    environment {
        BB_APP_CREDS = credentials('bb-app')
        AMPLIFY_APP_ID = credentials('amplify-app-id')
        WHITESOURCE_KEY = credentials('whitesource-key')
        WHITESOURCE_USER_KEY = credentials('whitesource-user-key')
        BUILD_PLATFORM = 'amplify' // amplify or netlify
    }
    stages {
        stage('Send start notification') {
            agent {
                dockerfile {
                    label 'linux'
                    dir '.jenkins'
                }
            }
            steps {
                dir('helpers') {
                    git(
                       url: 'https://bitbucket.org/rbdigital/pipeline-helpers.git',
                       credentialsId: 'bb-app',
                       branch: 'master'
                    )
                    sh 'sh ./setup.sh'
                    sh 'node src/notification/jenkins-start-build.js'
                }
            }
        }
        stage('source validation') {
            failFast true
            parallel {
                stage('linters') {
                    agent {
                        dockerfile {
                            label 'linux'
                            dir '.jenkins'
                        }
                    }
                    steps {
                        sh 'yarn --immutable'
                        sh 'yarn run lint'
                        sh 'yarn run tslint'
                    }
                }
                stage('unit tests') {
                    agent {
                        dockerfile {
                            label 'linux'
                            dir '.jenkins'
                        }
                    }
                    steps {
                        sh 'yarn --immutable'
                        sh 'yarn run test'
                    }
                }
                stage('Whitesource Verification') {
                    agent {
                        dockerfile {
                            label 'linux'
                            dir '.whitesource'
                        }
                    }
                    when {
                        expression {
                            return env.BRANCH_NAME = 'develop'
                        }
                    }
                    steps {
                        sh 'curl -LJO https://github.com/whitesource/unified-agent-distribution/raw/master/standAlone/wss_agent.sh'
                        sh 'sh ./wss_agent.sh -apiKey ${WHITESOURCE_KEY} -userKey ${WHITESOURCE_USER_KEY} -c ./wss-agent.config -project husky-gatsby-template -d ./'
                    }
                }
            }
        }
        stage('Amplify build status') {
            agent {
                dockerfile {
                    label 'linux'
                    dir '.jenkins'
                    additionalBuildArgs '--build-arg BUILD_PLATFORM=${BUILD_PLATFORM}'
                }
            }
            when {
                // run for sites deployed on amplify only
                expression { return BUILD_PLATFORM == 'amplify' }
            }
            steps {
                dir('helpers') {
                    git(
                       url: 'https://bitbucket.org/rbdigital/pipeline-helpers.git',
                       credentialsId: 'bb-app',
                       branch: 'master'
                    )
                    sh 'sh ./setup.sh'
                    sh 'printenv'
                    withAWS(credentials: 'aws-key-cicd-automation', region: 'eu-central-1'){
                        sh 'node src/build-status/amplify-build-status.js'
                        sh 'cat website_url.txt'
                    }
                    stash includes: 'website_url.txt', name: 'website_url.txt'
                }
            }
        }
        stage('Netlify build and deploy') {
            agent {
                dockerfile {
                    label 'linux'
                    dir '.jenkins'
                    additionalBuildArgs '--build-arg BUILD_PLATFORM=${BUILD_PLATFORM}'
                }
            }
            when {
                // run for sites deployed on netlify only
                expression { return BUILD_PLATFORM == 'netlify' }
            }
            steps {
                sh 'yarn --immutable'
                withCredentials([
                    string(credentialsId: 'netlify-site-id', variable: 'NETLIFY_SITE_ID'),
                    string(credentialsId: 'netlify-auth-token', variable: 'NETLIFY_AUTH_TOKEN')
                ]) {
                    sh 'netlify status'
                    sh 'printenv'
                    sh 'netlify build --context deploy-preview'
                    script {
                        def deploy_output = sh(script: 'netlify deploy', returnStdout: true)
                        writeFile file: 'netlify-deploy-log.txt', text: "${deploy_output}"
                    }
                    sh 'cat netlify-deploy-log.txt'
                    script {
                        sh 'echo cat netlify-deploy-log.txt | grep "Website Draft URL:" | cut -d " "  -f 4'
                        def website_url = sh(script: "cat netlify-deploy-log.txt | grep 'Website Draft URL:' | egrep -o 'https?://[^ ]+'", returnStdout: true)
                        writeFile file: 'website_url.txt', text: "${website_url}"
                    }
                    sh 'cat website_url.txt'
                }
                stash includes: 'website_url.txt', name: 'website_url.txt'
            }
        }
        stage('e2e tests') {
            agent {
                docker {
                    image 'cypress/base:10'
                    label 'linux'
                }
            }
            when {
                expression { false }  // skip this stage
            }
            steps {
                sh 'rm -rf node_modules'
                unstash 'website_url.txt'
                sh 'cat website_url.txt'
                sh 'yarn'
                script {
                    def WEBSITE_URL = sh(script: 'cat website_url.txt', returnStdout: true)
                    sh "echo ${WEBSITE_URL}"
                    sh "yarn run e2e-tests --env WEBSITE_URL=\"${WEBSITE_URL}\""
                }
            }
        }
        stage('webpage validation') {
            parallel {
                stage('run webhint') {
                    agent {
                        docker {
                            image 'buildkite/puppeteer:latest'
                            label 'linux'
                        }
                    }
                    when {
                        expression { false } // skip this stage
                    }
                    steps {
                        unstash 'website_url.txt'
                        dir('webhint') {
                            git(
                                url: 'https://bitbucket.org/rbdigital/webhint.git',
                                credentialsId: 'bb-app',
                                branch: 'master'
                            )
                            sh 'yarn'
                            script {
                                def WEBSITE_URL = sh(script: 'cat ../website_url.txt', returnStdout: true)
                                sh "echo \"${WEBSITE_URL}\""
                                sh "MAIN_URL=\"${WEBSITE_URL}\" node index.js"
                            }
                        }
                        // publish html
                        publishHTML target: [
                            allowMissing: false,
                            alwaysLinkToLastBuild: false,
                            keepAll: true,
                            reportDir: 'webhint/hint-report',
                            reportFiles: sh(returnStdout: true, script: 'cat webhint/report-url.txt'),
                            reportName: 'Hint Report'
                        ]
                    }
                }
                stage('run lighthouse') {
                    agent {
                        docker {
                            image 'femtopixel/google-lighthouse:v8.0.0'
                            label 'linux'
                            args '--security-opt seccomp=$WORKSPACE/lighthouse/chrome.json'
                        }
                    }
                    steps {
                        unstash 'website_url.txt'
                        sh 'lighthouse --version'
                        script {
                            def WEBSITE_URL = sh(script: 'cat website_url.txt', returnStdout: true)
                            sh "lighthouse --quiet --output html --chrome-flags='--headless' --output-path ./lighthouse/mobile.html ${WEBSITE_URL}"
                            sh "lighthouse --quiet --output html --chrome-flags='--headless' --output-path ./lighthouse/desktop.html --preset desktop ${WEBSITE_URL}"
                        }

                        // publish html
                        publishHTML target: [
                            allowMissing: false,
                            alwaysLinkToLastBuild: false,
                            keepAll: true,
                            reportDir: 'lighthouse',
                            reportFiles: 'mobile.html,desktop.html',
                            reportName: 'Lighthouse Report'
                        ]
                    }
                }
            }
        }
    }
    post {
        always {
            echo 'One way or another, I have finished'
        }
        success {
            node('linux') {
                script {
                    checkout scm
                    def nodeImage = docker.build('node-image', './.jenkins')
                    nodeImage.inside {
                        unstash 'website_url.txt'
                        dir('pipeline-helpers') {
                            git(
                                url: 'https://bitbucket.org/rbdigital/pipeline-helpers.git',
                                credentialsId: 'bb-app',
                                branch: 'master'
                            )
                            script {
                                sh 'sh ./setup.sh'
                                def WEBSITE_URL = sh(script: 'cat ../website_url.txt', returnStdout: true)
                                sh "WEBSITE_URL=\"${WEBSITE_URL}\" node src/comment/build-success.js"
                                sh "WEBSITE_URL=\"${WEBSITE_URL}\" node src/notification/jenkins-build-success.js"
                            }
                        }
                    }
                }
            }
        }
        failure {
            node('linux') {
                script {
                    checkout scm
                    def nodeImage = docker.build('node-image', './.jenkins')

                    nodeImage.inside {
                        dir('pipeline-helpers') {
                            git(
                                url: 'https://bitbucket.org/rbdigital/pipeline-helpers.git',
                                credentialsId: 'bb-app',
                                branch: 'master'
                            )
                            sh 'sh ./setup.sh'
                            sh 'node src/notification/jenkins-build-fail.js'
                        }
                    }
                }
            }
        }
    }
}