#!groovy

node {
	// Globals
	BuildDir   = pwd tmp: true
	SrcDir     = pwd tmp: false
	RemoteRepo = 'git@github.com:cforall/cforall.git'
	ArchiveUrl = 'https://cforall.uwaterloo.ca/jenkins/job/Cforall_Distribute_Ref/lastSuccessfulBuild/artifact/*zip*/archive.zip'

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

	currentBuild.result = "SUCCESS"

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

		PrepRepo();

		def name = GetArchive();

		PushRepo(name);
	}

}

def GetTarName() {
	def files = findFiles(glob: 'archive/cfa-cc-*.tar.gz')
	echo "found: ${files[0].name}"
	return files[0].name - '.tar.gz';
}

def PrepRepo() {
	stage('Clone') { // for display purposes
		dir (BuildDir) {
		    sh 'rm -rf *'
			sshagent (credentials: ['github_key_jun1']) {
				sh "git clone --bare ${RemoteRepo} repo"
			}
			dir ('repo') {
				sh "mkdir .git"
				sh "mv * .git"
				sh "git init"
			}
		}
	}
}

def GetArchive() {
	def tarball
	stage('Unzip') { // for display purposes
		dir (BuildDir) {
			sh "wget -q ${ArchiveUrl}"
			sh "unzip archive.zip"
			tarball = GetTarName();
			sh "tar -xzf archive/${tarball}.tar.gz"
			sh "mv ${tarball}/* repo/."
		}
	}

	return tarball
}

def PushRepo(name) {
	stage('Push') { // for display purposes
		dir ("${BuildDir}/repo") {
			sh "git add -A"
			sh "git status"
			sh "git diff-index --quiet HEAD || git commit -m 'Push from build machine: ${name}'"
			sshagent (credentials: ['github_key_jun1']) {
				sh "git push origin master"
			}
		}
	}
}
