#!groovy

import groovy.transform.Field

// For skipping stages
import org.jenkinsci.plugins.pipeline.modeldefinition.Utils

// wrapper around stage declaretion to be more verbose
// and allow showing as skipped in the UI
def BuildStage(String name, boolean run, Closure block ) {
	echo " -------- ${name} -------- "
	if(run) {
		stage(name, block)
	} else {
		stage(name) { Utils.markStageSkippedForConditional(STAGE_NAME) }
	}
}

//===========================================================================================================
// Common compilation routines
//===========================================================================================================
def Clean() {
	BuildStage('Cleanup', true) {
		// clean the build by wipping the build directory
		dir(BuildDir) {
			deleteDir()
		}
	}
}

def Checkout(commitHash = null) {
	BuildStage('Checkout', true) {
		//checkout the source code and clean the repo
		if(commitHash) {
			echo "Checking out commit <${commitHash}>"
			final scmVars = checkout([$class: 'GitSCM', branches: [[name: commitHash ]],
				userRemoteConfigs: [[
					url: 'cforall@plg.uwaterloo.ca:software/cfa/cfa-cc',
					credentialsId: 'git_key_aug20']]
			])
			echo GitLogMessage(scmVars.GIT_COMMIT, scmVars.GIT_PREVIOUS_COMMIT)
		} else {
			final scmVars = checkout scm
			echo GitLogMessage(scmVars.GIT_COMMIT, scmVars.GIT_PREVIOUS_COMMIT)
		}
	}
}

//===========================================================================================================
//Routine responsible of sending the email notification once the build is completed
//===========================================================================================================
@NonCPS
def SplitLines(String text) {
	def list = []

	text.eachLine {
		list += it
	}

	return list
}

def ConstructGitLogMessage(String oldRef, String newRef) {
	def revText = sh(returnStdout: true, script: "git rev-list ${oldRef}..${newRef}").trim()
	def revList = SplitLines( revText )

	def gitUpdate = ""
	revList.each { rev ->
		def type = sh(returnStdout: true, script: "git cat-file -t ${rev}").trim()
		gitUpdate = gitUpdate + "       via  ${rev} (${type})"
	}

	def rev = oldRef
	def type = sh(returnStdout: true, script: "git cat-file -t ${rev}").trim()
	gitUpdate = gitUpdate + "      from  ${rev} (${type})"

	def gitLog    = sh(returnStdout: true, script: "git rev-list --format=short ${oldRef}...${newRef}").trim()

	def gitDiff   = sh(returnStdout: true, script: "git diff --stat --color ${newRef} ${oldRef}").trim()
	gitDiff = gitDiff.replace('[32m', '<span style="color: #00AA00;">')
	gitDiff = gitDiff.replace('[31m', '<span style="color: #AA0000;">')
	gitDiff = gitDiff.replace('[m', '</span>')

	return """
<p>- Changes -------------------------------------------------------------</p>

<pre>
The branch ${env.BRANCH_NAME} has been updated.
${gitUpdate}
</pre>

<p>- Log -----------------------------------------------------------------</p>

<pre>
${gitLog}
</pre>

<p>-----------------------------------------------------------------------</p>
<pre>
Summary of changes:
${gitDiff}
</pre>
"""
}

EmailMessage = ''
def GitLogMessage(String oldRef = '', String newRef = '') {
	if(!EmailMessage) {
		if (!oldRef) { return "\nERROR retrieveing current git information!\n"  }
		if (!newRef) { return "\nERROR retrieveing previous git information!\n" }

		echo "Constructing new git message"

		EmailMessage = ConstructGitLogMessage(oldRef, newRef)
	}
	else {
		echo "Reusing previously constructed message"
	}
	return EmailMessage;
}

return this;