// Mirror of ci/Jenkinsfile.titan-iac for multibranch discovery.
pipeline {
  agent {
    kubernetes {
      defaultContainer 'python'
      yaml """
apiVersion: v1
kind: Pod
spec:
  nodeSelector:
    hardware: rpi5
    kubernetes.io/arch: arm64
    node-role.kubernetes.io/worker: "true"
  containers:
    - name: python
      image: python:3.12-slim
      command:
        - cat
      tty: true
"""
    }
  }
  environment {
    PIP_DISABLE_PIP_VERSION_CHECK = '1'
    PYTHONUNBUFFERED = '1'
    SUITE_NAME = 'titan-iac'
    PUSHGATEWAY_URL = 'http://platform-quality-gateway.monitoring.svc.cluster.local:9091'
  }
  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }
    stage('Install deps') {
      steps {
        sh 'pip install --no-cache-dir -r ci/requirements.txt'
      }
    }
    stage('Run quality gate') {
      steps {
        sh '''
          set -eu
          mkdir -p build
          set +e
          python3 -m testing.quality_gate --profile jenkins --build-dir build
          quality_gate_rc=$?
          set -e
          printf '%s\n' "${quality_gate_rc}" > build/quality-gate.rc
        '''
      }
    }
    stage('Publish test metrics') {
      steps {
        sh '''
          set -eu
          export JUNIT_GLOB='build/junit-*.xml'
          export QUALITY_GATE_EXIT_CODE_PATH='build/quality-gate.rc'
          export QUALITY_GATE_SUMMARY_PATH='build/quality-gate-summary.json'
          python3 ci/scripts/publish_test_metrics.py
        '''
      }
    }
    stage('Enforce quality gate') {
      steps {
        sh '''
          set -eu
          test "$(cat build/quality-gate.rc 2>/dev/null || echo 1)" -eq 0
        '''
      }
    }
    stage('Resolve Flux branch') {
      steps {
        script {
          env.FLUX_BRANCH = sh(
            returnStdout: true,
            script: "awk '/branch:/{print $2; exit}' clusters/atlas/flux-system/gotk-sync.yaml"
          ).trim()
          if (!env.FLUX_BRANCH) {
            error('Flux branch not found in gotk-sync.yaml')
          }
          echo "Flux branch: ${env.FLUX_BRANCH}"
        }
      }
    }
    stage('Promote') {
      when {
        expression {
          def branch = env.BRANCH_NAME ?: (env.GIT_BRANCH ?: '').replaceFirst('origin/', '')
          return env.FLUX_BRANCH && branch == env.FLUX_BRANCH
        }
      }
      steps {
        withCredentials([usernamePassword(credentialsId: 'gitea-pat', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_TOKEN')]) {
          sh '''
            set +x
            git config user.email "jenkins@bstein.dev"
            git config user.name "jenkins"
            git remote set-url origin https://${GIT_USER}:${GIT_TOKEN}@scm.bstein.dev/bstein/titan-iac.git
            git push origin HEAD:${FLUX_BRANCH}
          '''
        }
      }
    }
  }
  post {
    always {
      script {
        if (fileExists('build/junit-unit.xml') || fileExists('build/junit-glue.xml')) {
          try {
            junit allowEmptyResults: true, testResults: 'build/junit-*.xml'
          } catch (Throwable err) {
            echo "junit step unavailable: ${err.class.simpleName}"
          }
        }
      }
      archiveArtifacts artifacts: 'build/**', allowEmptyArchive: true, fingerprint: true
    }
  }
}
