#!groovy

node {
    try {
        stage('Download') {
            step([$class: 'WsCleanup'])

            echo "Downloading build artifact.."
            withCredentials([
                string(credentialsId: "${aws_env}_aws_access_key", variable: 'AWS_ACCESS_KEY_ID'),
                string(credentialsId: "${aws_env}_aws_secret_key", variable: 'AWS_SECRET_ACCESS_KEY')
            ]) {
                sh 'aws s3 cp --region eu-west-1 s3://${dns_name}-codedeploy/notifications-admin-${DEPLOY_BUILD_NUMBER}.zip source.zip'
            }

            echo "Extracting build artifact.."
            sh 'unzip -q source.zip'
        }
        stage('Deploy') {
            lock(cf_space) {
                withCredentials([
                    string(credentialsId: 'paas_username', variable: 'CF_USERNAME'),
                    string(credentialsId: 'paas_password', variable: 'CF_PASSWORD')
                ]) {
                    sh "CF_SPACE=${cf_space} make cf-deploy-with-docker"
                }
            }
        }
    } catch(err) {
        currentBuild.result = 'FAILURE'
        echo "PaaS deployment to ${cf_space} failed: ${err}"
        try {
            slackSend channel: '#govuk-notify', message: "PaaS deployment to ${cf_space} failed: <${env.BUILD_URL}|${env.JOB_NAME} - #${env.BUILD_NUMBER}>", color: 'danger'
        } catch(err2) {
            echo "Sending Slack message failed: ${err2}"
        }
    } finally {
        stage('Post-build') {
            if (cf_space == 'production') {
                try {
                    slackSend channel: '#govuk-notify', message: "PaaS deployment to ${cf_space} finished: <${env.BUILD_URL}|${env.JOB_NAME} - #${env.BUILD_NUMBER}>", color: 'good'
                } catch(err2) {
                    echo "Sending Slack message failed: ${err2}"
                }
            }
            try {
                step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'notify-support+jenkins@digital.cabinet-office.gov.uk', sendToIndividuals: false])
            } catch(err2) {
                echo "Sending email failed: ${err2}"
            }
        }
    }
}
