#!groovy

node ('master') {

	user_email = ''
	test_list = ''

	prepare_build()

	try {

		stage('Checkout') {
			checkout scm
		}

		stage('Building x86') {
			regen_tests('i386')
		}

		stage('Building x64') {
			regen_tests('x86_64')
		}

		stage('Patching') {
			make_patch()
		}

		stage('Email') {
			email()
		}
	} 
	catch (Exception caughtError) {
		email_error()

		throw caughtError
	}
}

def prepare_build() {
	properties ([ 													\
		[$class: 'ParametersDefinitionProperty', 								\
			parameterDefinitions: [ 									\
				[$class: 'StringParameterDefinition',						\
					description: 'Who required the test',					\
					name: 'pEmail',									\
				],												\
				[$class: 'StringParameterDefinition',						\
					description: 'Space separated list of tests to run',			\
					name: 'pTests',									\
				],												\
			],
		]])

	user_email = pEmail;
	test_list  = pTests;
}

def regen_tests( String arch ) {

	def install_dir = pwd tmp: true
		
	//Configure the conpilation (Output is not relevant)
	//Use the current directory as the installation target so nothing
	//escapes the sandbox
	//Also specify the compiler by hand
	sh "./configure CXX=clang++ --host=${arch} --with-backend-compiler=gcc-6 --prefix=${install_dir} --enable-silent-rules --quiet"

	//Compile the project
	sh 'make -j 8 --no-print-directory install'

	//Regenerate the desired tests
	sh "src/tests/test.py --regenerate-expected ${test_list}"

	//Clean everything from the last build
	sh 'make maintainer-clean > /dev/null'
}

def make_patch() {

	def target_dir = pwd tmp: true

	//Add every file so new files appear in the diff
	sh 'git add .'

	//Create a patch file
	sh "git diff --cached --binary > ${target_dir}/result.patch"
}

def email() {

	def target_dir = pwd tmp: true

	def email_subject = "[cforall dashboard][TEST REGEN# ${env.BUILD_NUMBER}] - Result"
	def email_body = """This is an automated email from the Jenkins build machine. It was
generated http://plg2:8082/dashboard."""

	//send email notification
	emailext body: email_body, subject: email_subject, to: user_email, attachmentsPattern: '${target_dir}/result.patch'
}

def email_error() {

	def target_dir = pwd tmp: true

	def email_subject = "[cforall dashboard][TEST REGEN# ${env.BUILD_NUMBER}] - FAILURE"
	def email_body = """This is an automated email from the Jenkins build machine. It was
generated http://plg2:8082/dashboard.

Test generation encoutered an error please see attached logs

-----------------------------------------------------------------------"""

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