

node ('master'){

	def err = null
	def stage_name
	def log_needed = false
	currentBuild.result = "SUCCESS"

	try {

		stage 'Checkout'

			//checkout the source code and clean the repo
			checkout scm
			sh 'git clean -dfq'

		stage 'Build'

			stage_name = 'Build'

			//configure the conpilation
			//Don't remove outputs for the clean and configure unless errors are present
			sh 'make clean > /dev/null'
			sh 'CC=gcc-4.9 CXX=g++-4.9 ./configure > /dev/null'
			sh 'make -j 8'

		stage 'Test'

			stage_name = 'Test'

			dir ('src/example') {
				sh './runTests.sh'
			}

		stage 'Cleanup'

			email("SUCCESS", false)
	}

	catch (Exception caughtError) {
		err = caughtError
		log_needed = false
		currentBuild.result = "FAILURE"

		switch(stage) {
			case 'Test' :
				currentBuild.result = "TEST FAILURE"
				break
			default :
				break
		}
	}

	finally {
		//Send email with final results
		email(currentBuild.result, log_needed)

		/* Must re-throw exception to propagate error */
		if (err) {
			throw err
		}
	}
}

def email(String status, boolean log) {
	//Since tokenizer doesn't work, figure stuff out from the environnement variables and command line
	//Configurations for email format
	def project_name = (env.JOB_NAME =~ /(.+)\/.+/)[0][1].toLowerCase()

	def email_subject = "[${project_name} git] UNNAMED PROJECT branch ${env.BRANCH_NAME} - Build # ${env.BUILD_NUMBER} - ${status}!"
	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".

	The branch ${env.BRANCH_NAME} has been updated.

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

	// def config = new File('/u/cforall/software/cfa/cfa-cc/config').text
	// def email_to = (config =~ /mailinglist ?= ?(.+)/)[0][1]
	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: log
}
