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+)$/
          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 -DgenerateBackupPoms=false -DnewVersion="$BUILD_VERSION"'
        }
      }
    }

    stage('Prepare OWASP cache') {
      steps {
        lock(resource: 'owasp-nvd-cache') {
          withMaven(maven: 'maven-3.9.16', globalMavenSettingsConfig: 'locusworks-settings') {
            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
        }
      }
    }

    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"'
        }
      }
    }
  }

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