#!groovy

import groovy.transform.Field

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

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

node {
	// Globals
	BuildDir  = pwd tmp: true
	SrcDir    = pwd tmp: false
	Settings  = null
	Version   = ''

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

	currentBuild.result = "SUCCESS"

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

			Version = GetVersion( build )

			Configure()

			Package()

			Test()

			Archive()
		}

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

}

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

def Configure() {
	Tools.BuildStage('Configure', true) {
		// Configure must be run inside the tree
		dir (SrcDir) {
			// Generate the necessary build files
			sh './autogen.sh'
		}

		// Build outside of the src tree to ease cleaning
		dir (BuildDir) {
			// Configure the compilation (Output is not relevant)
			// Use the current directory as the installation target so nothing escapes the sandbox
			// Also specify the compiler by hand
			sh "${SrcDir}/configure CXX=g++-9 CC=gcc-9 AR=gcc-ar RANLIB=gcc-ranlib --quiet"

			// Configure libcfa
			sh 'make -j 8 --no-print-directory configure-libcfa'
		}
	}
}

def Package() {
	Tools.BuildStage('Package', true) {
		dir (BuildDir) {
			sh "make VERSION=${Version} dist"
		}
	}
}

def Test() {
	Tools.BuildStage('Test', true) {
		dir (BuildDir) {
			sh "make VERSION=${Version} distcheck -j 8"
		}
	}
}

def Archive() {
	Tools.BuildStage('Archive', true) {
		dir (BuildDir) {
			archiveArtifacts artifacts: "cfa-cc-*.tar.gz", fingerprint: true
		}
	}
}


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

