#!/usr/bin/env groovy

this.node_name = 'crushinator'
this.colors = [$class: 'AnsiColorBuildWrapper', 'colorMapName': 'XTerm', 'defaultFg': 1, 'defaultBg': 2]
this.timestamper = [$class: 'TimestamperBuildWrapper']

def cleanWorkspace() {
    sh "rm -rf tmp/junit tmp/capybara tmp/codeclimate"
}

try {
  this.branch = env.GITHUB_PR_SOURCE_BRANCH || env.branch
} catch (e) {
  this.branch = branch
}

def git(branch, refspec) {
    [
            $class           : 'GitSCM',
            extensions: [
		    [$class: 'CleanBeforeCheckout'],
	            [$class: 'SubmoduleOption', parentCredentials: true, recursiveSubmodules: true]
            ],
            branches         : [[name: branch]],
            userRemoteConfigs: [
                    [
                            credentialsId: 'cf670269-124d-4f18-bcd8-d22fbcb29565',
                            refspec      : refspec,
                            url          : 'git@github.com:3scale/system.git'
                    ]
            ]
    ]
}

try {
    head_ref = "pull/${GITHUB_PR_NUMBER}/head"
    this.head = git("origin/${head_ref}", "+refs/${head_ref}:refs/remotes/origin/${head_ref}")

    scm_ref = "pull/${GITHUB_PR_NUMBER}/${GITHUB_PR_COND_REF}"
    this.ref = git("origin/${scm_ref}", "+refs/${scm_ref}:refs/remotes/origin/${scm_ref}")
    this.build_name = env.GITHUB_PR_SOURCE_BRANCH
} catch (e) {
    echo "not a PR, trying branch ${branch} (error: ${e})"
    this.head = git("refs/heads/${branch}", "+refs/heads/${branch}:refs/remotes/origin/${branch}")
    this.ref = this.head
    this.build_name = branch
}

this.cache = true
try {
    this.cache = env.CACHE == 'true'
} catch (e) {
    echo "error setting cache: ${e}"
    this.cache = true
}

this.archive_logs = false
try {
    this.archive_logs = env.ARCHIVE_LOGS == 'true'
} catch (e) { }

this.commit = env.GIT_COMMIT

if (!this.commit) {
    this.commit = env.GITHUB_PR_HEAD_SHA
}

try {
    echo "BUILD_CAUSE_MANUALTRIGGER: ${env.BUILD_CAUSE_MANUALTRIGGER}"

    if (env.BUILD_CAUSE_MANUALTRIGGER == 'true') {
        percy_enable = env.PERCY_ENABLE
    }
} catch (e) {
    echo "Could not set percy enabled to 1 : ${e}"
}

this.status = false

def begin() {
    stage 'Checkout'
    node(node_name) {
        wrap(timestamper) {
            cleanWorkspace()
            checkout head
            step([$class: 'GitHubSetCommitStatusBuilder'])
        }
    }
    this.status = true
}

def report() {
    stage 'Report'
    node('master') {
        wrap(timestamper) {

            timeout(10) {
                cleanWorkspace()

                catchError {
                    echo "unstashing 1"
                    try { unstash "junit-1" } catch (e) { }
                    echo "unstashing 2"
                    try { unstash "junit-2" } catch (e) { }
                    echo "unstashing 3"
                    try { unstash "junit-3" } catch (e) { }
                    echo "unstashing 4"
                    try { unstash "junit-4" } catch (e) { }
                    echo "unstashing 5"
                    try { unstash "junit-5" } catch (e) { }
                    echo "unstashing 6"
                    try { unstash "junit-6" } catch (e) { }
                    echo "unstashing percy"
                    try { unstash "junit-percy" } catch (e) { }

                    echo 'Publish Test Results'
                    step([$class: 'JUnitResultArchiver', testResults: 'tmp/junit/**/*.xml'])
                }
            }
        }

	if (status) {
            echo "Setting GitHub commit status to ${currentBuild.result}"
            step([$class: 'GitHubCommitNotifier', resultOnFailure: 'FAILURE'])
        }
    }
}

def make_build(kind, node_name = this.node_name, proxy = 0) {

    def multijob = kind // for some reason, in node block, kind changes its value


    node(node_name) {
        wrap(timestamper) {

            cleanWorkspace()

            timeout(20) { // minutes
                checkout ref

                withEnv(["MULTIJOB_KIND=${multijob}",
                         "GIT_BRANCH=${branch}",
                         "GIT_COMMIT=${commit}",
                         "PROXY_ENABLED=${proxy}"]) {

                    wrap(colors) {
                        if (!cache) {
                            try {
                                sh "make clean-cache"
                            } catch (e) {
                                echo "Failed to clean the cache"
                            }
                        }

                        try {
                            timeout(25) {
			      withCredentials([
			          usernameColonPassword(credentialsId: '3f923ac9-69e5-4a98-b87a-f66af4b79bdf', variable: 'BUNDLE_GEMINABOX__3SCA__NET'),
			          usernameColonPassword(credentialsId: 'gems.contribsys.com', variable: 'BUNDLE_GEMS__CONTRIBSYS__COM')
				]) {
                                sh "make"
                              }
                            }
                            echo "make succeeded"
                        } catch (e) {
                            echo "make failed: ${e}"
                            currentBuild.result = 'FAILURE'
                        }
                    }
                    timeout(5) {
                        if (this.archive_logs) {
                            sh "mkdir -p tmp/log/${multijob} && find log -type f -iname '*.log' -exec mv {} tmp/log/${multijob}/ ';'"
                        } else {
                            sh "find log -type f -iname '*.log' -exec rm {} ';'"
                        }

                        echo 'Archive tmp'
                        try {
                          archive 'tmp/**/*'
                        }
                        catch (e) {
                          // Probably due to network error (master in BCN and slaves in US)
                          // Bonus point for who solves this. May be related to
                          // https://issues.jenkins-ci.org/browse/JENKINS-21905
                          echo "[WARNING] Archiving artifacts failed: ${e}"
                          echo "Continuing ..."
                        }
                    }

                    timeout(5) {
                        //echo 'Publish Test Results'
                        echo "Stash JUnit results for ${multijob}"
                        try {
                            stash includes: 'tmp/junit/**/*.xml', name: "junit-${multijob}"
                        } catch (e) {
                            // this really should not happen, all the tests should produce some junit
                            echo "Failed to stash ${multijob} junit files"
                        }
                        //step([$class: 'JUnitResultArchiver', testResults: 'tmp/junit/**/*.xml'])
                    }

                    cleanWorkspace()
                }
            }
        }
    }
}

return this
