#!/usr/bin/env bash
# Shared by thin and golden CI. Source-build because kitsubito's GLIBC 2.35
# cannot run the release asset (GLIBC 2.39). Keep the clone outside the workspace.
set -euo pipefail
# 0.4.1 fixes file-root enumeration dropping present doc evidence (IR-109).
WANT=0.4.1
BIN="$HOME/.local/bin/traceable-reqs"
mode="${1:-precheck}"
case "$mode" in precheck|install) ;; *) echo 'usage: traceable-reqs.sh [precheck|install]' >&2; exit 2;; esac

# [impl->REQ-CI-CHECKER-PIN-PRECHECK]
probe() {
  actual=missing
  version_exit=not-run
  if [ -x "$BIN" ]; then
    version_exit=0
    actual="$("$BIN" --version)" || version_exit=$?
  elif [ -e "$BIN" ]; then
    actual=not-executable
  fi
  printf 'CHECKER_PIN pin=%s box=%q version_exit=%s binary=%q\n' \
    "$WANT" "$actual" "$version_exit" "$BIN"
  [ "$version_exit" = 0 ] && [ "$actual" = "traceable-reqs $WANT" ]
}

if ! probe; then
  echo '::warning title=Checker pin/runner disagreement::The runner does not supply the pinned checker; see CHECKER_PIN above. Coverage has not run.'
  if [ -z "${GH_TOKEN:-}" ]; then
    echo '::error title=Checker repair credential missing::TRACEABLE_REQS_TOKEN is absent. Install the pinned checker on the runner or have the operator provision read access to BigscreenVR/traceable-reqs. No clone or build attempted.'
    exit 1
  fi
  echo 'CHECKER_REPAIR credential=present action=source-build (repository access not yet verified)'
  if [ "$mode" = install ]; then
    SRC="${RUNNER_TEMP:?RUNNER_TEMP is required for checker repair}/tr-src"
    rm -rf "$SRC"
    git clone --depth 1 --branch "v$WANT" \
      "https://x-access-token:${GH_TOKEN}@github.com/BigscreenVR/traceable-reqs" "$SRC"
    cargo build --release --manifest-path "$SRC/rust/Cargo.toml"
    mkdir -p "$HOME/.local/bin"
    cp "$SRC/rust/target/release/traceable-reqs" "$BIN"
    if ! probe; then
      echo '::error title=Checker repair version mismatch::The repaired binary still does not match CHECKER_PIN. Coverage will not run.'
      exit 1
    fi
  fi
fi
if [ "$mode" = install ]; then
  ln -sf "$BIN" ./traceable-reqs
fi
