#!/usr/bin/env groovy

pipeline {
    agent any
    options {
        timestamps()
        ansiColor('xterm')
    }
    stages {
        // surprisingly no need to explicitly checkout, jenkins will do this for you
        stage('Manta test') {
            steps {
                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.
                    sh '''#!/bin/bash
                        set -x
                        git_branch=$BRANCH_NAME
                        case $git_branch in
                            PR-*) git_branch=$CHANGE_BRANCH ;;
                        esac
                        url=$(echo $GIT_URL|sed -e 's#https://#git@#' -e 's#/#:#')
                        sed -i -e s#https://.*#$url# -e "s#fetch = .*#fetch = +refs/heads/*:refs/remotes/origin/*#" .git/config
                        git fetch
                        git reset --hard $GIT_COMMIT
                        git diff --diff-filter=MARC origin/master... --name-only | egrep -i "[.](pp|yaml)$" || exit 0
                        manta -v -X everythingisawesome
                    '''
                }
            }
        }
        stage('Netboot image build') {
            when {
                branch 'PR-*'
            }
            steps {
                build(
                    job: 'video-coreservices/transcode_ubuntu_image/jenkins-master',
                    parameters: [string(name: 'puppet_branch', value: env.CHANGE_BRANCH)],
                    wait: false,
                )
            }
        }
    }
}
