#!/usr/bin/env groovy
@Library('flexo-libs')_
pipeline {
    agent any

    parameters {
        string(name: 'puppet_branch', defaultValue: 'production', description: 'Puppet branch used to build netboot image')
    }
    triggers {
        cron(env.BRANCH_NAME == 'master' ? '0 9 * * *' : '')
    }
    options {
        timestamps()
            ansiColor('xterm')
    }
    stages {
        stage('Prepare build environment') {
            steps {
                script {
                    puppet_branch = params.puppet_branch
                    if (puppet_branch == 'master') {
                        puppet_branch = 'production'
                    }
                }
                // TODO eventually we should use packer library: https://git.xarth.tv/video-coreservices/package-builder/blob/master/Jenkinsfile#L3-L5
                sh "make packer"
                sshagent(credentials: ['git-aws-read-key']) {
                    // This is a really ugly part. By default jenkins checks out only the branch you work with.
                    // Since we need to compare with the master branch we need to fetch necessary information.
                    // But jenkins uses https to fetch and I don't know what credentials we can use.
                    // Because of that I run this in the context of ssh-agent with proper credentials and
                    // I modify .git/config to use ssh instead of https.
                    // Each time we merge to master we mirror changes to the jenkins-master. We need to do this
                    // because puppet changes trigger a lot of builds and GHE has a limit of 2000 commit status updates per commit.
                    // We need to push empty commit when number of builds is close to 2000 and we can't do this for the
                    // master branch since it is protected
                    sh '''#!/bin/bash
                        set -x
                        [ "$BRANCH_NAME" != "master" ] && exit
                        url=$(echo $GIT_URL|sed -e 's#https://#git@#' -e 's#/#:#')
                        sed -i -e s#https://.*#$url# -e s#$BRANCH_NAME#*#g .git/config
                        git fetch
                        git checkout jenkins-master
                        git reset --hard $GIT_COMMIT
                        git push -f --set-upstream origin jenkins-master
                    '''
                    sh '''#!/bin/bash
                        set -x
                        [ "$BRANCH_NAME" != "jenkins-master" ] && exit
                        (((BUILD_ID % 1900) != 0)) && exit
                        url=$(echo $GIT_URL|sed -e 's#https://#git@#' -e 's#/#:#')
                        sed -i -e s#https://.*#$url# -e s#$BRANCH_NAME#*#g .git/config
                        git fetch
                        git checkout jenkins-master
                        git commit --allow-empty -m "Empty commit to make GHE happy"
                        git push -f --set-upstream origin jenkins-master
                    '''
                }
            }
        }
        stage('Build images') {
            parallel {
                stage('bionic') {
                    steps {
                        sshagent(credentials: ['git-aws-read-key']) {
                            sh """
                                make PUPPET_BRANCH=${puppet_branch} jenkins_bionic
                                """
                        }
                    }
                }
            }
        }
        stage('Upload artifacts') {
            steps {
                script {
                    env.DEPLOY_ENV = "staging"
                    roleAccount = "045385815217"
                    region = "us-east-2"
                    if (env.BRANCH_NAME == 'master') {
                            env.DEPLOY_ENV = "production"
                            region = "us-west-2"
                            roleAccount = "805315462901"
                    }
                    withAgentAWS(role: "provisioner-s3-reverse-proxy-jenkins-assume-role", roleAccount: roleAccount, region: region) {
                        sh """
                            ./jenkins-deploy.sh ${env.DEPLOY_ENV} ${puppet_branch}
                            """
                    }
                }
            }
        }
        stage('Run tests') {
            parallel {
                stage('bionic') {
                    steps {
                        script {
                            env.DEPLOY_ENV = "staging"
                            if (env.BRANCH_NAME == 'master') {
                                env.DEPLOY_ENV = "production"
                            }
                        }
                        withAgentAWS(role: "netboot_validator_sqs_role", roleAccount: "277437172290", region: "us-west-2") {
                            sh "DISTRO_CODENAME=bionic ./jenkins-run-tests.sh ${env.DEPLOY_ENV}"
                        }
                    }
                }
            }
        }
        stage('Publish metrics') {
            steps {
                script {
                    env.DEPLOY_ENV = "staging"
                    if (env.BRANCH_NAME == 'master') {
                        env.DEPLOY_ENV = "production"
                    }
                }
                withAgentAWS(role: "CloudwatchAgentLogs", roleAccount: "277437172290", region: "us-west-2") {
                    sh """
                        ./packer build -var deploy_env=${env.DEPLOY_ENV} cw-metrics.json
                        """
                }
            }
        }
    }
// TODO email notifications are broken on the jenkins right now, we need to figure out alternative way
// to be notified on failures
//    post {
//        failure {
//            mail to: 'video-coreservices-alerts@justin.tv',
//                 subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
//                 body: "Something is wrong with ${env.BUILD_URL}"
//        }
//    }
}
