pipeline {
  agent { label 'java-test' }

  environment {
    NODE_BASE_IMAGE = '172.31.198.7:10082/java-project/node:22-alpine'
    NGINX_BASE_IMAGE = '172.31.198.7:10082/java-project/nginx:1.27-alpine'
    TEST_SITE_ROOT = '/www/wwwroot/test-pda-global.buggoglobal.com'
    TEST_SITE_URL = 'https://test-pda-global.buggoglobal.com/'
  }

  options {
    timestamps()
    disableConcurrentBuilds()
  }

  stages {
    stage('确认提交版本') {
      steps {
        script {
          env.SOURCE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
        }
        sh 'git log -1 --oneline'
      }
    }

    stage('测试并构建 H5 验收站') {
      steps {
        sh '''
          set -eu
          docker run --rm --pull=never \
            -u "$(id -u):$(id -g)" \
            -e HOME=/tmp \
            -v "$WORKSPACE:/workspace" \
            -w /workspace \
            "$NODE_BASE_IMAGE" \
            sh -lc 'npm ci && npm test && npm run build:h5'

          test -f dist/build/h5/index.html
          grep -R -F '当前绑定仓没有匹配的待签收或签收中退货单' dist/build/h5/assets >/dev/null
        '''
      }
    }

    stage('发布测试站') {
      steps {
        sh '''
          set -eu
          target="$(readlink -f "$TEST_SITE_ROOT")"
          test "$target" = '/www/wwwroot/test-pda-global.buggoglobal.com'

          docker run --rm --pull=never \
            -e SOURCE_TAG="$SOURCE_TAG" \
            -v "$WORKSPACE/dist/build/h5:/source:ro" \
            -v "$target:/deploy" \
            "$NGINX_BASE_IMAGE" \
            sh -eu -c '
              next="/deploy/.codex-next-$SOURCE_TAG"
              previous="/deploy/.codex-previous-$SOURCE_TAG"
              rm -rf "$next" "$previous"
              mkdir -p "$next" "$previous"
              cp -a /source/. "$next/"
              test -f "$next/index.html"

              rollback() {
                for entry in index.html assets static; do
                  rm -rf "/deploy/$entry"
                  if [ -e "$previous/$entry" ]; then mv "$previous/$entry" "/deploy/$entry"; fi
                done
              }
              committed=0
              trap '\''if [ "$committed" -eq 0 ]; then rollback; fi'\'' EXIT HUP INT TERM

              for entry in index.html assets static; do
                if [ -e "/deploy/$entry" ]; then mv "/deploy/$entry" "$previous/$entry"; fi
              done
              for entry in assets static; do
                if [ -e "$next/$entry" ]; then mv "$next/$entry" "/deploy/$entry"; fi
              done
              mv "$next/index.html" /deploy/index.html
              committed=1
              trap - EXIT HUP INT TERM
              rm -rf "$next" "$previous"
            '
        '''
      }
    }

    stage('发布检查') {
      steps {
        sh '''
          set -eu
          curl -fsS "$TEST_SITE_URL" | grep -F '<title>' >/dev/null
        '''
      }
    }
  }
}
