#!groovy

//===========================================================================================================
// Main compilation routines
//===========================================================================================================

def trigger_build(String arch) {
	def result = build job: 'Cforall/master', 		\
		parameters: [						\
			[$class: 'BooleanParameterValue', 		\
			  name: 'isFullBuild', 				\
			  value: true], 					\
			[$class: 'StringParameterValue', 		\
			  name: 'buildArchitecture', 			\
			  value: arch]					\
		]

	echo(result.result)
	echo(result.absoluteUrl)
}

def push_build() {
	//Don't use the build_stage function which outputs the compiler
	stage 'Push'

		status_prefix = 'Push'

		def out_dir = pwd tmp: true
		sh "mkdir -p ${out_dir}"

		//checkout the code to make sure this is a valid git repo
		checkout scm

		collect_git_info()

		//parse git logs to find what changed
		sh "git remote > ${out_dir}/GIT_REMOTE"
		git_remote = readFile("${out_dir}/GIT_REMOTE")
		remoteDoLangExists = git_remote.contains("DoLang")

		if( !remoteDoLangExists ) {
			sh 'git remote add DoLang git@gitlab.do-lang.org:internal/cfa-cc.git'
		}

		//sh "GIT_SSH_COMMAND=\"ssh -v\" git push DoLang ${gitRefNewValue}:master"
		echo('BUILD NOT PUSH SINCE DO-LANG SERVER WAS DOWN')
}

//Helper routine to collect information about the git history
def collect_git_info() {

	//create the temporary output directory in case it doesn't already exist
	def out_dir = pwd tmp: true
	sh "mkdir -p ${out_dir}"

	//parse git logs to find what changed
	dir("../Cforall_Full_Build@script") {
		sh "git reflog > ${out_dir}/GIT_COMMIT"
	}
	git_reflog = readFile("${out_dir}/GIT_COMMIT")
	gitRefOldValue = (git_reflog =~ /moving from (.+) to (.+)/)[0][1]
	gitRefNewValue = (git_reflog =~ /moving from (.+) to (.+)/)[0][2]
}

//===========================================================================================================
// Main loop of the compilation
//===========================================================================================================

node ('master') {
	def err = null

	try {
		//Prevent the build from exceeding 30 minutes
		timeout(60) {

			//Wrap build to add timestamp to command line
			wrap([$class: 'TimestamperBuildWrapper']) {

				stage 'Build'

					results = [null, null]

					parallel (
						x64: {
							trigger_build('64-bit')
						},
						x32: {
							trigger_build('32-bit')
						}
					)

				//Push latest changes to do-lang repo
				push_build()
			}
		}
	}

	//If an exception is caught we need to change the status and remember to
	//attach the build log to the email
	catch (Exception caughtError) {
		//rethrow error later
		err = caughtError

		//Store the result of the build log
		currentBuild.result = "${status_prefix} FAILURE".trim()

		//Send email to notify the failure
		promote_email(currentBuild.result)
	}

	finally {
		//Must re-throw exception to propagate error
		if (err) {
			throw err
		}
	}
}
//===========================================================================================================
//Routine responsible of sending the email notification once the build is completed
//===========================================================================================================

//Email notification on a full build failure
def promote_email(String status) {
	//Since tokenizer doesn't work, figure stuff out from the environnement variables and command line
	//Configurations for email format
	def email_subject = "[cforall git][PROMOTE - FAILURE]"
	def email_body = """This is an automated email from the Jenkins build machine. It was
generated because of a git hooks/post-receive script following
a ref change was pushed to the repository containing
the project "UNNAMED PROJECT".

Check console output at ${env.BUILD_URL} to view the results.

- Status --------------------------------------------------------------

PROMOTE FAILURE - ${status}
"""

	def email_to = "pabuhr@uwaterloo.ca, rschlunt@uwaterloo.ca, a3moss@uwaterloo.ca, tdelisle@uwaterloo.ca, brice.dobry@huawei.com"

	//send email notification
	emailext body: email_body, subject: email_subject, to: email_to, attachLog: true
}
