#!/bin/bash
# CHECK-closed-artifacts: Q127's gate.
#
# Two legs, both required:
#   1. the guard, over this tree (pins + cells + contract)
#   2. the guard's own selftest (six fixtures: one control, five mutants)
#
# Exit codes follow the repo's tools/ contract:
#   0 = every pinned blob is the one its closed record landed, and its cell is green
#   1 = a graded fault (a repair reverted or drifted, a cell red, the guard unfit)
#   2 = could not grade (no python3, no guard, or the guard could not read the tree)
set -u

HERE=$(cd -- "$(dirname -- "$(readlink -f -- "$0")")" && pwd) || {
    echo "CHECK: cannot resolve the gate's own directory -- cannot grade." >&2
    exit 2
}

if ! command -v python3 >/dev/null 2>&1; then
    echo "CHECK: python3 not on PATH -- cannot grade." >&2
    exit 2
fi

if [ ! -f "$HERE/closed_artifact_guard.py" ]; then
    echo "CHECK: $HERE/closed_artifact_guard.py is missing -- cannot grade." >&2
    exit 2
fi

python3 "$HERE/closed_artifact_guard.py"
rc=$?
case $rc in
    0) ;;
    1) echo "CHECK: a closed repair has been reverted or drifted (rc 1)." >&2; exit 1 ;;
    *) echo "CHECK: the guard could not read this tree (rc $rc)." >&2; exit 2 ;;
esac

python3 "$HERE/closed_artifact_guard.py" --selftest >/dev/null
rc=$?
case $rc in
    0) ;;
    1) echo "CHECK: the guard's own selftest is red -- it no longer grades (rc 1)." >&2; exit 1 ;;
    *) echo "CHECK: the guard's selftest could not run (rc $rc)." >&2; exit 2 ;;
esac

echo "CHECK: Q109's and Q120's repairs are byte-identical to what landed, and both cells run green."
exit 0
