/*
 * Jakarta Validation API
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */

@Library('releng-pipeline') _

// Avoid running the pipeline on branch indexing
if (currentBuild.getBuildCauses().toString().contains('BranchIndexingCause')) {
	print "INFO: Build skipped due to trigger being Branch Indexing"
	currentBuild.result = 'NOT_BUILT'
	return
}

pipeline {
	agent {
		label 'basic'
	}
	tools {
		maven 'apache-maven-3.9.11'
		jdk 'openjdk-jdk25-latest'
	}
	options {
		buildDiscarder logRotator(daysToKeepStr: '30', numToKeepStr: '10')
		disableConcurrentBuilds(abortPrevious: false)
	}
	parameters {
		string(
				name: 'RELEASE_VERSION',
				defaultValue: '',
				description: 'The version to be released, e.g. 4.0.0.',
				trim: true
		)
		string(
				name: 'DEVELOPMENT_VERSION',
				defaultValue: '',
				description: 'The next version to be used after the release, e.g. 4.0.1-SNAPSHOT.',
				trim: true
		)
		choice(name: 'LICENSE_TO_APPLY', choices: ['apache', 'eftl'], description: 'Select which license should be applied.')
	}
	stages {
		stage('Publish Release to Maven Central') {
			when {
				beforeAgent true
				// Releases must be triggered explicitly
				// This is just for safety; normally the Jenkins job for this pipeline
				// should be configured to "Suppress automatic SCM triggering"
				// See https://stackoverflow.com/questions/58259326/prevent-jenkins-multibranch-pipeline-from-triggering-builds-for-new-branches
				triggeredBy cause: "UserIdCause"
			}
			steps {
				script {
					// Check that all the necessary parameters are set
					if (!params.RELEASE_VERSION) {
						throw new IllegalArgumentException("Missing value for parameter RELEASE_VERSION.")
					}
					if (!params.DEVELOPMENT_VERSION) {
						throw new IllegalArgumentException("Missing value for parameter DEVELOPMENT_VERSION.")
					}
					def specVersion = sh(script: "echo \"${params.RELEASE_VERSION}\" | awk -F'.' '{print \$1\".\"\$2}'", returnStdout: true).trim()

					echo "Performing release for version ${specVersion} (${params.RELEASE_VERSION}) on branch ${env.GIT_BRANCH}"

					sshagent(['github-bot-ssh']) {
						withCredentials([file(credentialsId: 'secret-subkeys.asc', variable: 'KEYRING')]) {
							withMaven(mavenLocalRepo: env.WORKSPACE_TMP + '/.m2repository') {
								sh 'gpg --batch --import "${KEYRING}"'
								sh 'for fpr in $(gpg --list-keys --with-colons  | awk -F: \'/fpr:/ {print $10}\' | sort -u); do echo -e "5\ny\n" |  gpg --batch --command-fd 0 --expert --edit-key ${fpr} trust; done'

								// Set up git so that we can create commits
								sh 'git config --local user.name "eclipse-validation-bot"'
								sh 'git config --local user.email "validation-bot@eclipse.org"'

								// update version:
								sh "./mvnw clean versions:set -DnewVersion=${params.RELEASE_VERSION} -DgenerateBackupPoms=false"

								// commit and tag the "release version":
								sh "git commit -a -m '[Jenkins release job] Preparing release ${params.RELEASE_VERSION}'"
								sh "git tag -a -m 'Release ${params.RELEASE_VERSION}' ${params.RELEASE_VERSION}"

								// deploy to Maven Central:
								sh "./mvnw clean deploy -Poss-release -Prelease -Plicense-${params.LICENSE_TO_APPLY} -Pdocumentation-pdf -DskipTests=true "

								// reset the version back to dev:
								sh "./mvnw versions:set -DnewVersion=${params.DEVELOPMENT_VERSION} -DgenerateBackupPoms=false"

								// commit the dev version and push all back to git:
								sh "git commit -a -m '[Jenkins release job] Preparing next development iteration'"

								sh "git push origin HEAD:${env.GIT_BRANCH}"
								sh "git push origin ${params.RELEASE_VERSION}"

								sshagent(['projects-storage.eclipse.org-bot-ssh']) {
									sh "ssh genie.validation@projects-storage.eclipse.org mkdir -p /home/data/httpd/download.eclipse.org/ee4j/bean-validation/${specVersion}"
									sh "sha256sum distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.zip >> distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.info"
									sh "sha256sum distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.tar.gz >> distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.info"
									sh "ls -l distribution/target/validation-tck-dist-${params.RELEASE_VERSION}* >> distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.info"

									sh "sha256sum distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.zip | cut -d ' ' -f 1 >> distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.zip.sha256"
									sh "sha256sum distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.tar.gz | cut -d ' ' -f 1 >> distribution/target/validation-tck-dist-${params.RELEASE_VERSION}.tar.gz.sha256"

									sh "rsync -avz --include='validation-tck-dist-*' --exclude='*' distribution/target/ genie.validation@projects-storage.eclipse.org:/home/data/httpd/download.eclipse.org/ee4j/bean-validation/${specVersion}/"
								}
							}
						}
					}
				}
			}
		}
	}
}
