#!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' ) },
					gcc_6_x86: { trigger_build( 'gcc-6',   'x86' ) },
					gcc_5_x64: { trigger_build( 'gcc-5',   'x64' ) },
					gcc_5_x86: { trigger_build( 'gcc-5',   'x86' ) },
					clang_x64: { trigger_build( 'clang',   'x64' ) },
					clang_x86: { trigger_build( 'clang',   'x86' ) },
				)
			}
		}

		promote_email(true)
	}

	//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_email(false)
	}

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

def trigger_build(String cc, String arch) {
	def result = build job: 'Cforall/master', 		\
		parameters: [						\
			[$class: 'StringParameterValue', 		\
			  name: 'Compiler', 				\
			  value: cc],					\
			[$class: 'StringParameterValue', 		\
			  name: 'Architecture', 			\
			  value: arch],					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'RunAllTests', 				\
			  value: true], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'RunBenchmark', 			\
			  value: true], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'BuildDocumentation', 		\
			  value: true], 					\
			[$class: 'BooleanParameterValue', 		\
			  name: 'Publish', 				\
			  value: true], 				\
			[$class: 'BooleanParameterValue', 		\
			  name: 'Silent', 				\
			  value: true], 					\
		],								\
		propagate: false

	echo(result.result)

	if(result.result != 'SUCCESS') {
		sh("wget -q -O - http://localhost:8084/jenkins/job/Cforall/job/master/${result.number}/consoleText")
		error(result.result)
	}
}

//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_email(boolean success) {
	echo('notifying users')

	def result = success ? "PROMOTE - SUCCESS" : "PROMOTE - FAILURE"

	//Since tokenizer doesn't work, figure stuff out from the environnement variables and command line
	//Configurations for email format
	def email_subject = "[cforall git][${result}]"
	def email_body = """<p>This is an automated email from the Jenkins build machine. It was
generated following the result of the C\u2200 nightly build.</p>

<p>Check console output at ${env.BUILD_URL} to view the results.</p>

<p>- Status --------------------------------------------------------------</p>

<p>${result}</p>

<p>- Performance ---------------------------------------------------------</p>

<img src="https://cforall.uwaterloo.ca/jenkins/job/Cforall/job/master/plot/Compilation/getPlot?index=0" >

<p>- Logs ----------------------------------------------------------------</p>
"""

	def email_to = "cforall@lists.uwaterloo.ca"

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