#!groovy

import groovy.transform.Field

// For skipping stages
import org.jenkinsci.plugins.pipeline.modeldefinition.Utils

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

node('master') {
	// Globals
	BuildDir  = pwd tmp: true
	SrcDir    = pwd tmp: false
	Settings  = null

	// Local variables
	def err = null
	def log_needed = false

	currentBuild.result = "SUCCESS"

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

			final commit, build
			(commit, build) = prepare_build()

			node('x64') {
				BuildDir  = pwd tmp: true
				SrcDir    = pwd tmp: false

				Tools.Clean()

				Tools.Checkout( commit )

				final version = GetVersion( build )
			}

			// Update the build directories when exiting the node
			BuildDir  = pwd tmp: true
			SrcDir    = pwd tmp: false
		}
	}

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

		// echo err.toString()

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

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

	finally {
		// //Send email with final results if this is not a full build
		// email(log_needed)

		// echo 'Distribution Completed'

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

//===========================================================================================================
// Main compilation routines
//===========================================================================================================
def GetVersion(build) {
	final pver = sh(
		returnStdout: true,
		script: "sed 's/AC_INIT(\\[cfa-cc\\],\\[\\(.*\\)\\],\\[cforall@plg.uwaterloo.ca\\])/\\1/;t;d' ${SrcDir}/configure.ac"
	).trim()

	final version = "${pver}.${build}"

	echo "Package Version: ${pver}"
	echo "Build   Version: ${build}"
	echo "Long    Version: ${version}"

	return version
}


//===========================================================================================================
// Helper classes/variables/routines
//===========================================================================================================
def prepare_build() {
	// prepare the properties
	properties ([ 													\
		buildDiscarder(logRotator(										\
			artifactDaysToKeepStr: '',									\
			artifactNumToKeepStr: '',									\
			daysToKeepStr: '730',										\
			numToKeepStr: '1000'										\
		)),														\
		[$class: 'ParametersDefinitionProperty', 								\
			parameterDefinitions: [ 									\
				[$class: 'StringParameterDefinition',						\
					description: 'The git commit to checkout',				\
					name: 'GitRef',									\
					defaultValue: '',  								\
				],												\
				[$class: 'StringParameterDefinition',						\
					description: 'Build Number to put into the version',			\
					name: 'Build',									\
					defaultValue: '0',  								\
				],												\
			],
		]])

	// It's unfortunate but it looks like we need to checkout the entire repo just to get
	// - the pretty git printer
	// - Jenkins.tools
	checkout scm

	Tools = load "Jenkins/tools.groovy"

	currentBuild.description = "Distributing Tarball"
	def ref = params.GitRef ? params.GitRef : "HEAD"
	echo "Distributing git commit ${ref}"

	return [params.GitRef, params.Build]
}

