#!/usr/bin/env bash
# Run the published Controlplane's own tests using the consuming backend's pins.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")"/../../.. && pwd)"
OUT_DIR="${OUT_DIR:-/tmp/crm-source-backed-ci}"
mkdir -p "$OUT_DIR"
cd "$REPO_ROOT/backend"

# Dependency tests are not part of the backend's normal go mod tidy closure.
# Resolve their test-only dependencies in an isolated modfile; keep the real
# backend pins and sibling-module replacements, without dirtying the checkout.
modfile="$(mktemp "$REPO_ROOT/backend/.controlplane-recovery.XXXXXX.mod")"
sumfile="${modfile%.mod}.sum"
trap 'rm -f "$modfile" "$sumfile"' EXIT
cp go.mod "$modfile"
cp go.sum "$sumfile"
export GOWORK=off
export GOFLAGS="-modfile=$modfile -mod=mod"

controlplane=github.com/pingcap-inc/nexuscrm-controlplane
expected_version="$(go list -m -f '{{.Version}}' "$controlplane")"
tests=(
  TestApplyMetadataInitializesPermissionStateBeforePackWriters
  TestVerifyPathFailsClosedForMissingPhysicalColumnWithoutHashDrift
  TestExplicitApplyAllRepairsMissingPhysicalColumn
  TestRegisterInstalledRuntimeMetadataRestoresInstalledSourceBackedRuntimeState
  TestRebuildDerivedRestoresInstalledSourceBackedRuntimeState
  TestApplyAllRepairsMissingPhysicalColumnForInstalledSourceBackedPack
)
pattern="$(IFS='|'; echo "${tests[*]}")"
results="$OUT_DIR/controlplane-runtime-recovery-results.jsonl"
set +e
go test -tags integration "$controlplane" -run "^($pattern)$" -count=1 -timeout=10m -json >"$results"
rc=$?
set -e
if [[ "$rc" -ne 0 ]]; then
  # Go emits compiler/setup diagnostics as build-output, not test output.
  jq -r 'select(.Action == "output" or .Action == "build-output") | .Output' "$results" >&2
  exit "$rc"
fi
actual_version="$(go list -m -f '{{.Version}}' "$controlplane")"
if [[ "$actual_version" != "$expected_version" ]]; then
  echo "Controlplane test dependency resolution changed the production pin: $expected_version -> $actual_version" >&2
  exit 1
fi
for test_name in "${tests[@]}"; do
  jq -se --arg name "$test_name" 'any(.[]; .Test == $name and .Action == "pass")' "$results" >/dev/null || {
    echo "Required recovery proof did not run and pass: $test_name" >&2
    exit 1
  }
done
echo "Controlplane $actual_version: all ${#tests[@]} recovery proofs passed; evidence: $results"
