pipeline {
  agent any

  options {
    buildDiscarder(logRotator(numToKeepStr: '5'))
    disableConcurrentBuilds()
    skipDefaultCheckout(true)
    timestamps()
  }

  stages {
    stage('Checkout') {
      steps { checkout scm }
    }

    stage('Set version') {
      steps {
        script {
          String branch = env.BRANCH_NAME
          if (!branch) { error('BRANCH_NAME is unavailable; this pipeline must run as a multibranch job') }
          env.DEPLOY_BUILD = 'false'
          def releaseMatch = branch =~ /^release\/(\d+\.\d+(?:\.\d+)?)$/
          if (releaseMatch.matches()) {
            env.BUILD_VERSION = "${releaseMatch[0][1]}.${env.BUILD_NUMBER}-RELEASE"
            env.DEPLOY_BUILD = 'true'
          } else if (branch == 'develop') {
            env.BUILD_VERSION = "develop.${env.BUILD_NUMBER}-SNAPSHOT"
            env.DEPLOY_BUILD = 'true'
          } else {
            String safeBranch = branch.replaceAll(/[^A-Za-z0-9._-]/, '-')
            env.BUILD_VERSION = "0.0.${env.BUILD_NUMBER}-${safeBranch}-SNAPSHOT"
          }
          currentBuild.displayName = env.BUILD_VERSION
        }
        withMaven(maven: 'maven-3.9.16', globalMavenSettingsConfig: 'locusworks-settings') {
          sh 'mvn -B org.codehaus.mojo:versions-maven-plugin:2.21.0:set -DprocessAllModules=true -DgenerateBackupPoms=false -DnewVersion="$BUILD_VERSION"'
          sh 'mvn -B org.codehaus.mojo:versions-maven-plugin:2.21.0:set-property -Dproperty=current.version -DgenerateBackupPoms=false -DnewVersion="$BUILD_VERSION"'
        }
      }
    }

    stage('Prepare OWASP cache') {
      steps {
        lock(resource: 'owasp-nvd-cache') {
          withMaven(maven: 'maven-3.9.16', globalMavenSettingsConfig: 'locusworks-settings') {
            // Dependency-Check uses nvdApiKey from pom.xml.
            sh 'mkdir -p "$HOME/.cache/dependency-check"'
            sh 'mvn -B org.owasp:dependency-check-maven:13.0.0:update-only -DdataDirectory="$HOME/.cache/dependency-check"'
          }
        }
      }
    }

    stage('Build and test') {
      steps {
        withMaven(maven: 'maven-3.9.16', globalMavenSettingsConfig: 'locusworks-settings') {
          sh 'mvn -B clean verify -DdataDirectory="$HOME/.cache/dependency-check" -DautoUpdate=false -Dbuild.revision="$GIT_COMMIT"'
        }
      }
      post {
        always { junit allowEmptyResults: true, testResults: '**/target/surefire-reports/*.xml' }
        success {
          archiveArtifacts artifacts: '**/target/*.jar', fingerprint: true
          archiveArtifacts artifacts: '**/target/site/jacoco/**', fingerprint: true, allowEmptyArchive: true
        }
      }
    }

    stage('Build LaTeX') {
      when { branch pattern: 'release/**', comparator: 'GLOB' }
      steps {
        script {
          String gitCredentials = scm.userRemoteConfigs[0].credentialsId
          if (!gitCredentials) { error('Release builds require an SCM HTTPS username/password credential with permission to push tags') }
          withCredentials([gitUsernamePassword(credentialsId: gitCredentials, gitToolName: scm.gitTool ?: 'Default')]) {
            sh 'mkdir -p target && sh scripts/release-notes.sh generate "$BUILD_VERSION" > target/release-notes.md'
          }
        }
        sh 'awk -f scripts/release-notes.awk target/release-notes.md > docs/src/appendix/ReleaseNotes.tex'
        dir('docs/src') {
          sh '''
            mkdir -p ../../target/latex
            # Repeat to resolve cross-references and the table of contents.
            for pass in 1 2 3; do
              pdflatex -file-line-error -interaction=nonstopmode -halt-on-error -output-directory=../../target/latex portal.tex
            done
          '''
        }
        archiveArtifacts artifacts: 'target/latex/portal.pdf,target/release-notes.md,docs/src/appendix/ReleaseNotes.tex', fingerprint: true
      }
    }

    stage('Deploy') {
      when { expression { env.DEPLOY_BUILD == 'true' } }
      steps {
        withMaven(maven: 'maven-3.9.16', globalMavenSettingsConfig: 'locusworks-settings') {
          sh 'mvn -B deploy -DskipTests -Ddependency-check.skip=true -Dbuild.number="$BUILD_NUMBER" -Dbuild.revision="$GIT_COMMIT"'
        }
      }
    }
    stage('Tag release') {
      when { branch pattern: 'release/**', comparator: 'GLOB' }
      steps {
        script {
          withCredentials([gitUsernamePassword(credentialsId: scm.userRemoteConfigs[0].credentialsId, gitToolName: scm.gitTool ?: 'Default')]) {
            sh 'sh scripts/release-notes.sh publish "$BUILD_VERSION"'
          }
        }
      }
    }
  }

  post {
    success { echo "Published build ${env.BUILD_VERSION} successfully" }
    failure { echo "Build ${env.BUILD_VERSION ?: env.BUILD_NUMBER} failed" }
    cleanup { deleteDir() }
  }
}
