pipeline {
  agent {
    kubernetes {
      label 'lesavka-tests'
      defaultContainer 'rust-ci'
      yaml """
apiVersion: v1
kind: Pod
spec:
  nodeSelector:
    kubernetes.io/arch: arm64
    node-role.kubernetes.io/worker: "true"
  containers:
    - name: rust-ci
      image: rust:1.88-bookworm
      command: ["cat"]
      tty: true
      volumeMounts:
        - name: workspace-volume
          mountPath: /home/jenkins/agent
  volumes:
    - name: workspace-volume
      emptyDir: {}
"""
    }
  }

  options {
    disableConcurrentBuilds()
    disableResume()
  }

  parameters {
    booleanParam(name: 'PUSH_IMAGES', defaultValue: false, description: 'Push images to registry (enable for release runs)')
    string(name: 'QUALITY_GATE_PUSHGATEWAY_URL', defaultValue: 'http://platform-quality-gateway.monitoring.svc.cluster.local:9091', description: 'Pushgateway base URL for quality gate metrics')
    string(name: 'REGISTRY_CREDENTIALS_ID', defaultValue: 'registry-bstein-dev', description: 'Jenkins credentials id for registry.bstein.dev')
  }

  environment {
    REGISTRY = 'registry.bstein.dev'
    IMAGE_PREFIX = "${REGISTRY}/lesavka"
    CARGO_TERM_COLOR = 'always'
    DOCKER_BUILDKIT = '1'
  }

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

    stage('Bootstrap CI Toolchain') {
      steps {
        container('rust-ci') {
          sh '''
            set -eu
            apt-get update
            DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
              python3 \
              curl \
              file \
              clang \
              llvm \
              pkg-config \
              libssl-dev \
              ca-certificates \
              libgstreamer1.0-dev \
              libgstreamer-plugins-base1.0-dev \
              protobuf-compiler \
              libpango1.0-dev \
              libcairo2-dev \
              libgdk-pixbuf-2.0-dev \
              libgtk-4-dev
            rm -rf /var/lib/apt/lists/*
            rustup component add rustfmt llvm-tools-preview clippy
            git config --global --add safe.directory "$WORKSPACE"
            if ! cargo llvm-cov --version >/dev/null 2>&1; then
              cargo install --locked cargo-llvm-cov
            fi
          '''
        }
      }
    }

    stage('Style Docs LOC Naming') {
      steps {
        container('rust-ci') {
          sh 'scripts/ci/hygiene_gate.sh'
        }
      }
    }

    stage('Coverage') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/quality_gate.sh'
        }
      }
    }

    stage('Tests') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/test_gate.sh'
        }
      }
    }

    stage('Media Reliability') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/media_reliability_gate.sh'
        }
      }
    }

    stage('Gate Glue') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/gate_glue_gate.sh'
        }
      }
    }

    stage('SonarQube') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/sonarqube_gate.sh'
        }
      }
    }

    stage('Build Dist') {
      steps {
        container('rust-ci') {
          sh 'scripts/ci/build-dist.sh'
        }
      }
    }

    stage('Supply Chain Artifact Security') {
      steps {
        container('rust-ci') {
          sh 'QUALITY_GATE_PUSHGATEWAY_URL="${QUALITY_GATE_PUSHGATEWAY_URL}" scripts/ci/supply_chain_gate.sh'
        }
      }
    }

    stage('Docker Login') {
      when {
        expression { return params.PUSH_IMAGES }
      }
      steps {
        withCredentials([
          usernamePassword(
            credentialsId: params.REGISTRY_CREDENTIALS_ID,
            usernameVariable: 'REGISTRY_USER',
            passwordVariable: 'REGISTRY_PASS'
          )
        ]) {
          sh 'echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin'
        }
      }
    }

    stage('Build Images') {
      when {
        expression { return params.PUSH_IMAGES }
      }
      steps {
        sh 'PUSH_IMAGES=${PUSH_IMAGES} scripts/ci/build-images.sh'
      }
    }
  }

  post {
    always {
      script {
        try {
          archiveArtifacts artifacts: 'dist/**,target/test-gate/**,target/quality-gate/**,target/hygiene-gate/**,target/media-reliability-gate/**,target/gate-glue-gate/**,target/sonarqube-gate/**,target/supply-chain-gate/**', fingerprint: true, allowEmptyArchive: true
        } catch (Throwable err) {
          echo "archive step unavailable: ${err.class.simpleName}"
        }
      }
    }
  }
}
