#!groovy

//===========================================================================================================
// Main compilation routine
//===========================================================================================================
//Compilation script is done here but environnement set-up and error handling is done in main loop
def cfa_build(boolean full_build) {
	build_stage 'Checkout'
		def install_dir = pwd tmp: true
		//checkout the source code and clean the repo
		checkout scm

		//Clean all temporary files to make sure no artifacts of the previous build remain
		sh 'git clean -fdqx'

		//Reset the git repo so no local changes persist
		sh 'git reset --hard'

	build_stage 'Build'

		//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=${currentCC.cpp_cc} --with-backend-compiler=${currentCC.cfa_backend_cc} --prefix=${install_dir} --enable-silent-rules --quiet"

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

	build_stage 'Test'

		//Run the tests from the tests directory
		dir ('src/tests') {
			if (full_build) {
				sh 'make all-tests'
			}
			else {
				sh 'make'
			}
		}

	build_stage 'Cleanup'

		//do a maintainer-clean to make sure we need to remake from scratch
		sh 'make maintainer-clean > /dev/null'
}

def make_doc() {
	def err = null

	try {
		sh 'make clean > /dev/null'
		sh 'make > /dev/null 2>&1'
	}

	catch (Exception caughtError) {
		//rethrow error later
		err = caughtError

		sh 'cat *.log'
	}

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

def doc_build() {
	stage 'Documentation'

		status_prefix = 'Documentation'

		dir ('doc/user') {
			make_doc()
		}

		dir ('doc/refrat') {
			make_doc()
		}
}

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

		//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 push DoLang ${gitRefNewValue}:master"
}

//===========================================================================================================
// Helper classes/variables/routines to make the status and stage name easier to use
//===========================================================================================================
//Description of a compiler (Must be serializable since pipelines are persistent)
class CC_Desc implements Serializable {
	public String cc_name
	public String cpp_cc
	public String cfa_backend_cc

	CC_Desc(String cc_name, String cpp_cc, String cfa_backend_cc) {
		this.cc_name = cc_name
		this.cpp_cc = cpp_cc
		this.cfa_backend_cc = cfa_backend_cc
	}
}

//Global Variables defining the compiler and at which point in the build we are
// These variables are used but can't be declared before hand because of wierd scripting rules
// @Field String currentCC
// @Field String status_prefix

//Wrapper to sync stage name and status name
def build_stage(String name) {
	def stage_name = "${currentCC.cc_name} ${name}".trim()
	stage stage_name

		status_prefix = stage_name
}

//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
	gitRefName = env.BRANCH_NAME
	dir("../${gitRefName}@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'){

	boolean doPromoteBuild2DoLang
	def err = null
	def log_needed = false
	currentBuild.result = "SUCCESS"
	status_prefix = ''

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

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

				collect_git_info()

				properties ([ 									\
					[$class: 'ParametersDefinitionProperty', 				\
						parameterDefinitions: [ 					\
						[$class: 'BooleanParameterDefinition',  			\
						  defaultValue: false,  					\
						  description: 'If true, the build will be promoted to the do-lang git repository (on successful builds only)', \
						  name: 'promoteBuild2DoLang' 				\
						]] 									\
					]])

				doPromoteBuild2DoLang = promoteBuild2DoLang == 'true'

				echo "FULL BUILD = ${doPromoteBuild2DoLang}"

				//Compile using gcc-4.9
				currentCC = new CC_Desc('gcc-4.9', 'g++-4.9', 'gcc-4.9')
				cfa_build(doPromoteBuild2DoLang)

				//Compile latex documentation
				doc_build()

				if( doPromoteBuild2DoLang ) {
					//Compile using gcc-5
					currentCC = new CC_Desc('gcc-5', 'g++-5', 'gcc-5')
					cfa_build(true)

					//Compile using gcc-4.9
					currentCC = new CC_Desc('gcc-6', 'g++-6', 'gcc-6')
					cfa_build(true)

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

		//An error has occured, the build log is relevent
		log_needed = true

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

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

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

//===========================================================================================================
//Routine responsible of sending the email notification once the build is completed
//===========================================================================================================
def notify_result(boolean promote, Exception err, String status, boolean log) {
	echo 'Build completed, sending result notification'
	if(promote)	{
		if( err ) {
			promote_email(status)
		}
	}
	else {
		email(status, log)
	}
}

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

//Standard build email notification
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 gitLog = 'Error retrieving git logs'
	def gitDiff = 'Error retrieving git diff'

	try {

		sh "git rev-list --format=short ${gitRefOldValue}...${gitRefNewValue} > GIT_LOG"
		gitLog = readFile('GIT_LOG')

		sh "git diff --stat ${gitRefNewValue} ${gitRefOldValue} > GIT_DIFF"
		gitDiff = readFile('GIT_DIFF')
	}
	catch (Exception error) {}

	def email_subject = "[${project_name} git][BUILD# ${env.BUILD_NUMBER} - ${status}] - branch ${env.BRANCH_NAME}"
	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.
   via  ${gitRefOldValue} (commit)
  from  ${gitRefNewValue} (commit)

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

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

BUILD# ${env.BUILD_NUMBER} - ${status}

- Log -----------------------------------------------------------------
${gitLog}
-----------------------------------------------------------------------
Summary of changes:
${gitDiff}
"""

	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
}
