pipeline {
	agent { label "${params.AgentLabel}" }
	
	environment {
		CMAKE_BUILD_DIR = 'temp/cmake_jenkins'
		GH_TOKEN = credentials('tus_git_upload_token')
		GIT_URL = credentials('dsp56300_gitUrl')
	}
	parameters
	{
		string(name: 'Branch', defaultValue: "master", description: '')
		string(name: 'AgentLabel', defaultValue: "git && cmake", description: '')
		string(name: 'Platform', defaultValue: "", description: 'Visual Studio platform (-A), e.g. ARM64. Empty = the machine\'s own')
		string(name: 'Synths', defaultValue: "-Dgearmulator_SYNTH_OSIRUS=on", description: '')
		string(name: 'DisplayName', defaultValue: "?", description: '')
		string(name: 'UploadFolder', defaultValue: "", description: '')
		booleanParam(name: 'FXPlugins', defaultValue: false, description: '') 
		booleanParam(name: 'Deploy', defaultValue: true, description: '') 
		booleanParam(name: 'IntegrationTests', defaultValue: true, description: '')
		booleanParam(name: 'Upload', defaultValue: false, description: '') 
		booleanParam(name: 'GitHub', defaultValue: false, description: '') 
	}
	stages {
		stage("Checkout") {
			steps {
				script {
					currentBuild.displayName += " - ${platformName()} - ${params.Branch} - ${params.DisplayName}"
					currentBuild.description = "Integration Tests: ${params.IntegrationTests}\nDeploy: ${params.Deploy}\nUpload: ${params.Upload}\nGitHub: ${params.GitHub}"
				}
				doCheckout()
			}
		}
		stage('Compile') {
			steps {
				cmakeBuild();
			}
		}
		stage('Pack') {
			steps {
				doPack();
			}
		}
		stage('Integration Tests') {
			when {
				expression {
					return params.IntegrationTests
				}
			}
			steps {
				doIntegrationTests();
			}
		}
		stage('Deploy') {
			when {
				expression {
					return params.Deploy
				}
			}
			steps {
				doDeploy();
			}
		}
		stage('Upload') {
			when {
				expression {
					return params.Upload
				}
			}
			steps {
				doUpload();
			}
		}
		stage('GitHub') {
			when {
				expression {
					return params.GitHub
				}
			}
			steps {
				doGitHub();
			}
		}
	}
	post {
		always {
			script { notifyDiscord() }
		}
	}
}

def genericSh(cmd)
{
	if (isUnix())
	{
		sh cmd
	}
	else
	{
		bat cmd
	}
}

def formatArg(_arg)
{
	if(isUnix())
		return '$' + _arg
	else
		return '%' + _arg + '%'
}

def deleteFile(name)
{
	if(isUnix())
		sh "rm -f ${name}"
	else
		bat "del ${name}"
}

def buildFxPlugins()
{
	return params.FXPlugins ? 'on' : 'off'
}

def cmakeBuildDir()
{
	def dir = "${CMAKE_BUILD_DIR}_${params.Branch.replace('/', '_')}"
	// a build dir is fixed to one platform
	return params.Platform ? "${dir}_${params.Platform}" : dir
}

def platformName()
{
	return params.Platform ? "${params.AgentLabel} ${params.Platform}" : params.AgentLabel
}

def doCheckout()
{
	checkout(
		[$class: 'GitSCM'
		, branches: [[name: "*/${params.Branch}"]]
		, extensions: [
			[$class: 'SubmoduleOption'
			, disableSubmodules: false
			, parentCredentials: false
			, recursiveSubmodules: true
			, reference: ''
			, trackingSubmodules: false]
			// Fetch ONLY the branch we build. The default refspec pulls every branch of the repo, and
			// git's fetch.recurseSubmodules=on-demand then fetches the submodule commits each newly
			// fetched superproject commit points at. One branch whose submodule commit was never pushed
			// ("upload-pack: not our ref") therefore failed the fetch, and with it the checkout of every
			// build on every agent, no matter which branch it was building. honorRefspec applies the
			// narrow refspec to the initial clone too; tags are not used by this pipeline and pulling
			// them would drag in unrelated commits the same way.
			, [$class: 'CloneOption', honorRefspec: true, noTags: true, shallow: false, depth: 0, reference: '', timeout: 30]]
			, userRemoteConfigs: [[ url: GIT_URL, refspec: "+refs/heads/${params.Branch}:refs/remotes/origin/${params.Branch}" ]]
		]
	)
}

def getSynths()
{
    return "${env.synths}";
}

def cmakeBuild()
{
    def buildDir = cmakeBuildDir()
    def synths = getSynths()
    def fx = buildFxPlugins()
    def platform = params.Platform ? "-DCMAKE_GENERATOR_PLATFORM=${params.Platform}" : ""

	withCredentials([file(credentialsId: 'rclone_dsp56300_conf', variable: 'RCLONE_CONF')]) {
    	genericSh "cmake -Dgearmulator_SOURCE_DIR=../ -Dgearmulator_BINARY_DIR=../${buildDir} -Dgearmulator_BUILD_JUCEPLUGIN=on -Dgearmulator_BUILD_FX_PLUGIN=${fx} -DCMAKE_BUILD_TYPE=Release ${platform} ${synths} -P scripts/generate.cmake"
	}

	genericSh "cmake --build ${buildDir} --config Release"
}

def doIntegrationTests()
{
	withCredentials([file(credentialsId: 'rclone_dsp56300_conf', variable: 'RCLONE_CONF')]) {
    	dir(cmakeBuildDir()) {
    		genericSh "ctest -C Release -VV --output-on-failure"
    	}
	}
}

def doPack()
{
    def buildDir = cmakeBuildDir()
    
	dir(cmakeBuildDir()) {
		genericSh 'cmake -P ../../scripts/pack.cmake'
	}
	if("${params.UploadFolder}".contains("donators")) {
		genericSh "cmake -Dgearmulator_BINARY_DIR=${WORKSPACE}/${buildDir} -P scripts/packagesource.cmake"
	}
}

def copyArtefacts(local, remote)
{
    def buildDir = cmakeBuildDir()
    def synths = getSynths()
    
	withCredentials([file(credentialsId: 'rclone_dsp56300_conf', variable: 'RCLONE_CONF')]) {
		genericSh "cmake -Dgearmulator_BINARY_DIR=${buildDir} -DUPLOAD_LOCAL=${local} -DUPLOAD_REMOTE=${remote} -DFOLDER=${params.UploadFolder} ${synths} -P scripts/deployAll.cmake"
	}
}

def copySymbols()
{
    def buildDir = cmakeBuildDir()

	// archive debug symbols (.dSYM on macOS, .pdb on Windows) to the private deploy remote (the NAS), keyed
	// by branch+version so older releases stay symbolizable. Deploy only - symbols never go to the public upload.
	withCredentials([file(credentialsId: 'rclone_dsp56300_conf', variable: 'RCLONE_CONF')]) {
		genericSh "cmake -Dgearmulator_BINARY_DIR=${buildDir} -Dgearmulator_SOURCE_DIR=${WORKSPACE} -DBRANCH=${params.Branch} -DUPLOAD=1 -P scripts/deploySymbols.cmake"
	}
}

def doDeploy()
{
	copyArtefacts(1,0)
	copySymbols()
}

def doUpload()
{
	copyArtefacts(0,1)
}

def doGitHub()
{
    def buildDir = cmakeBuildDir()

	if("${params.UploadFolder}".contains("beta") || "${params.UploadFolder}" == "") {
		genericSh "cmake -Dgearmulator_SOURCE_DIR=${WORKSPACE} -Dgearmulator_BINARY_DIR=${WORKSPACE}/${buildDir} -P scripts/deployGitHub.cmake"
	}
}

def notifyDiscord()
{
	def result = currentBuild.currentResult
	def color  = result == 'SUCCESS' ? 3066993 : (result == 'ABORTED' ? 9807270 : 15158332)

	// writeJSON rather than hand built JSON on the command line: the payload goes to a file,
	// so there is no cmd-vs-sh quoting to get wrong on the windows/linux/mac agents
	writeJSON file: 'discord.json', json: [
		username: 'jenkins',
		embeds: [[
			title: currentBuild.fullDisplayName,
			url:   env.BUILD_URL,
			color: color,
			fields: [
				[name: 'Result',   value: result,            inline: true],
				[name: 'Platform', value: platformName(), inline: true],
				[name: 'Duration', value: currentBuild.durationString.replace(' and counting', ''), inline: true],
				[name: 'Branch',   value: params.Branch,     inline: true],
				[name: 'Synths',   value: params.Synths,     inline: false]
			]
		]]
	]

	// a discord outage must never turn a green build red
	try {
		withCredentials([string(credentialsId: 'discord_build_webhook', variable: 'DISCORD_HOOK')]) {
			genericSh 'curl -sS -H "Content-Type: application/json" -d @discord.json ' + formatArg('DISCORD_HOOK')
		}
	} catch(e) {
		echo "Discord notification failed: ${e}"
	}
	deleteFile('discord.json')
}
