#!groovy

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

node ('master') {
	def err = null

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

			stage('Build') {

				results = [null, null]

				parallel (
					gcc_6_x64: { trigger_build( 'gcc-6',   'x64', true  ) },
					gcc_6_x86: { trigger_build( 'gcc-6',   'x86', true  ) },
					gcc_5_x64: { trigger_build( 'gcc-5',   'x64', false ) },
					gcc_5_x86: { trigger_build( 'gcc-5',   'x86', false ) },
					gcc_4_x64: { trigger_build( 'gcc-4.9', 'x64', false ) },
					gcc_4_x86: { trigger_build( 'gcc-4.9', 'x86', false ) },
					clang_x64: { trigger_build( 'clang',   'x64', false ) },
					clang_x86: { trigger_build( 'clang',   'x86', false ) },
				)
			}

			//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) {
		echo('error caught')

		//rethrow error later
		err = caughtError

		//Store the result of the build log
		currentBuild.result = 'FAILURE'

		//Send email to notify the failure
		promote_failure_email()
	}

	finally {
		//Must re-throw exception to propagate error
		if (err) {
			throw err
		}
	}
}
//===========================================================================================================
// Main compilation routines
//===========================================================================================================

def trigger_build(String cc, String arch, Boolean publish) {
	def result = build job: 'Cforall/master', 		\
		parameters: [						\
			[$class: 'StringParameterValue', 		\
			  name: 'pCompiler', 				\
			  value: cc],					\
			[$class: 'StringParameterValue', 		\
			  name: 'pArchitecture', 			\
			  value: arch],					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'pRunAllTests', 			\
			  value: true], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'pRunBenchmark', 			\
			  value: true], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'pBuildDocumentation', 		\
			  value: true], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'pPublish', 				\
			  value: publish], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'pSilent', 				\
			  value: true], 					\
		],								\
		propagate: false

	echo(result.result)

	if(result.result != 'SUCCESS') {
		sh("wget -q -O - ${result.absoluteUrl}/consoleText")
		error(result.result)
	}
}

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]
}

//===========================================================================================================
//Routine responsible of sending the email notification once the build is completed
//===========================================================================================================

//Email notification on a full build failure
def promote_failure_email() {
	echo('notifying users')

	//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
"""

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

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