#!groovy

import groovy.transform.Field

// Globals
@Field def BuildDir  = null
@Field def SrcDir    = null
@Field def RemoteRepo = ''
@Field def ArchiveUrl = ''

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

node {
	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'
	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: ['git_key_aug2025']) {
				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: ['git_key_aug2025']) {
				sh "git push origin master"
			}
		}
	}
}
