// CI/CD for Gogs: push and pull requests targeting main.
// Builds, tests and packaging run inside Docker (DinD), not on the Jenkins host.
// Triggers are configured on the Jenkins job (Generic Webhook) + Gogs webhooks.

pipeline {
  agent {
    docker {
      image 'ura-ci-maven:21'
      label 'built-in'
      alwaysPull false
      args '-u root -v jenkins-m2-cache:/root/.m2 -e MAVEN_OPTS=-Xmx1024m'
    }
  }

  options {
    timestamps()
    disableConcurrentBuilds()
    timeout(time: 45, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '10'))
  }

  stages {
    stage('Checkout') {
      steps {
        script {
          def sha = env.pr_head_sha ?: env.after ?: 'main'
          if (!sha?.trim() || sha == 'null' || sha == '0000000000000000000000000000000000000000') {
            sha = 'main'
          }
          echo "Gogs event ref=${env.ref} action=${env.action} pr=#${env.pr_number} sha=${sha}"
          checkout([
            $class: 'GitSCM',
            branches: [[name: sha]],
            extensions: [[$class: 'CloneOption', shallow: false, noTags: false]],
            userRemoteConfigs: [[url: 'https://git.barcelos.dev/allan/jenkins-mfa-auth-plugin.git']]
          ])
        }
      }
    }

    stage('Test') {
      steps {
        sh 'mvn -B -ntp verify'
      }
      post {
        always {
          junit allowEmptyResults: true, testResults: 'target/surefire-reports/*.xml'
        }
      }
    }

    stage('Package') {
      steps {
        sh 'mvn -B -ntp -DskipTests -Dset.changelist package'
        sh 'ls -la target/*.hpi target/*.jar'
        archiveArtifacts artifacts: 'target/*.hpi,target/*-SNAPSHOT.jar', fingerprint: true
      }
    }

    stage('Release') {
      when {
        allOf {
          expression { env.ref == 'refs/heads/main' }
          expression { !env.pr_number?.trim() || env.pr_number == 'null' }
        }
      }
      steps {
        echo 'Release artifact is the archived HPI from this build (lastSuccessfulBuild).'
        sh '''
          set -e
          HPI=$(ls -1 target/*.hpi | head -1)
          echo "HPI=${HPI} size=$(wc -c < "$HPI") sha256=$(sha256sum "$HPI" | awk '{print $1}')"
        '''
      }
    }
  }

  post {
    always {
      sh 'chmod -R a+rwX "$WORKSPACE" || true'
    }
  }
}
