#!/usr/bin/env bash
# Install re-recorded venues' rows and commit them, rows only.
#
#   scripts/rerecord-commit [--no-commit] [--subject TEXT] OUT_DIR...
#
# Each OUT_DIR is a batch out directory scripts/rerecord-venue left (build.json, done.tsv,
# rows.jsonl, refusals.jsonl), copied here as it is. Run it in a checkout of the ref the venues
# were recorded at, or of a descendant that changes no product source:
#
#   1. The tracked tree must be clean. corpus-vulkan is built from it.
#   2. Every OUT_DIR's record must be this build (`batch-build this_build=yes` from
#      --batch-report: the executor ABI, the product's source fingerprint, the translation
#      semantics, and the Metal oracle). A row is current only at the build that recorded it, so
#      a product change between recording and this commit would commit stale rows; it is refused
#      before anything is installed.
#   3. Each OUT_DIR is installed into crates/metal2vulkan-validation/corpus by its backend's --batch-install (each
#      (case, slot)'s last evidence, through the store's validated writes).
#   4. Only candidate and refusal shards may have changed (crates/metal2vulkan-validation/corpus/observations/vulkan
#      and refusals/vulkan); anything else stops it before the commit,
#      with the tree left as it is for inspection.
#   5. The shards are committed (unless --no-commit) with --subject (default: one naming the
#      venues and the product) and a body listing each venue's installed rows and refusals. The
#      commit changes no product source, so the build, and every installed row, stays current.
#
# Then judge the commit: `corpus-status --c3` (C3's verdict per venue) at it. Metal rows are never
# written. Exit 0 when committed (or, with --no-commit, installed), 2 on a usage or
# precondition error, 1 on any other failure.
set -o pipefail

usage() {
    sed -n '2,/^# precondition error/p' "$0" | sed 's/^# \{0,1\}//' >&2
    exit 2
}
fail() { echo "rerecord-commit: $*" >&2; exit 2; }

commit=1
subject=
dirs=()
while [ "$#" -gt 0 ]; do
    case "$1" in
        --no-commit) commit=; shift ;;
        --subject) [ "$#" -ge 2 ] || usage; subject=$2; shift 2 ;;
        -h|--help) usage ;;
        -*) echo "rerecord-commit: unknown argument $1" >&2; usage ;;
        *) dirs+=("$1"); shift ;;
    esac
done
[ "${#dirs[@]}" -gt 0 ] || usage

root=$(git rev-parse --show-toplevel) || fail "not in a git checkout"
abs=()
for dir in "${dirs[@]}"; do
    [ -f "$dir/build.json" ] || fail "$dir has no build.json: not a batch out directory of a known build"
    abs+=("$(cd "$dir" && pwd -P)") || exit 2
done
cd "$root" || exit 2
[ -z "$(git status --porcelain --untracked-files=no)" ] ||
    fail "tracked files have changes: commit or remove them first"
head=$(git rev-parse HEAD) || exit 2

cargo build --release -p metal2vulkan-validation --bin corpus-vulkan ||
    { echo "rerecord-commit: build failed" >&2; exit 1; }
target=$(cargo metadata --format-version 1 --no-deps |
    python3 -c 'import json, sys; print(json.load(sys.stdin)["target_directory"])') || exit 1
# Copies, so no build in a shared target directory replaces them while they run.
bin=$(mktemp -d) || exit 1
trap 'rm -rf "$bin"' EXIT
cp "$target/release/corpus-vulkan" "$bin/" || exit 1

# record DIR: "backend metal_environment_id environment_id product executor_abi semantics oracle
# restricted_to" (the last "-" for an unrestricted batch)
record() {
    python3 - "$1/build.json" <<'PY'
import json, sys
b = json.load(open(sys.argv[1]))
print(b.get("backend", "vulkan"), b["metal_environment_id"], b["environment_id"], b["product"],
      b["executor_abi"], b["semantics_version"], b["oracle_abi"], b.get("restricted_to") or "-")
PY
}

# 2. Every record is this build, before anything is installed.
for dir in "${abs[@]}"; do
    read -r backend metal venue product executor semantics oracle restricted < <(record "$dir") ||
        fail "$dir/build.json does not parse"
    restrict=()
    [ "$restricted" = - ] || restrict=(--profiles-layer "$restricted")
    report=$("$bin/corpus-$backend" --batch-report --corpus crates/metal2vulkan-validation/corpus \
        --out "$dir" --metal-environment-id "$metal" --environment-id "$venue" "${restrict[@]}") ||
        { echo "rerecord-commit: --batch-report failed on $dir" >&2; exit 1; }
    line=${report%%$'\n'*}
    case "$line" in
        "batch-build this_build=yes"*) ;;
        *) fail "$dir ($venue) was not recorded by this build: ${line:0:300}" ;;
    esac
done

# 3. Install.
body=
venues=
for dir in "${abs[@]}"; do
    read -r backend metal venue product executor semantics oracle restricted < <(record "$dir")
    [ "$restricted" = - ] || venue="$venue@$restricted"
    out=$("$bin/corpus-$backend" --batch-install crates/metal2vulkan-validation/corpus --out "$dir") ||
        { echo "rerecord-commit: --batch-install failed on $dir" >&2; exit 1; }
    echo "$venue: $out"
    case "$out" in
        *" this_build=yes") ;;
        *) echo "rerecord-commit: $dir installed rows of another build: $out" >&2; exit 1 ;;
    esac
    rows=$(printf '%s' "$out" | sed -n 's/.* rows=\([0-9]*\) .*/\1/p')
    refusals=$(printf '%s' "$out" | sed -n 's/.* refusals=\([0-9]*\) .*/\1/p')
    body="$body
- $venue ($backend): $rows rows, $refusals refusals"
    venues="$venues${venues:+, }$venue"
done

# 4. Only candidate and refusal shards changed.
other=$(git status --porcelain --untracked-files=all | cut -c4- | grep -v -E \
    '^crates/metal2vulkan-validation/corpus/observations/(vulkan|refusals/vulkan)/[^/]+\.jsonl$')
[ -z "$other" ] || {
    echo "rerecord-commit: the install changed more than candidate and refusal shards:" >&2
    echo "$other" >&2
    exit 1
}
if [ -z "$(git status --porcelain --untracked-files=all)" ]; then
    echo "rerecord-commit: the installed rows and refusals are already committed; nothing to do"
    exit 0
fi
[ -n "$commit" ] || { echo "rerecord-commit: installed (not committed, --no-commit)"; exit 0; }

# 5. Commit, rows only.
git add -A -- crates/metal2vulkan-validation/corpus/observations/vulkan \
    crates/metal2vulkan-validation/corpus/observations/refusals/vulkan ||
    exit 1
[ -n "$subject" ] || subject="Record $venues at product ${product:0:12}"
git commit -q -m "$subject" -m "Rows and refusals recorded by one build (executor $executor, product
$product, semantics $semantics, oracle $oracle), installed at $head by
scripts/rerecord-commit. Only candidate and refusal shards change, so the product,
and every row installed here, stays current.
$body" || exit 1
changed=$(git diff --name-only HEAD^ HEAD | grep -v -E \
    '^crates/metal2vulkan-validation/corpus/observations/(vulkan|refusals/vulkan)/')
[ -z "$changed" ] || { echo "rerecord-commit: the commit changed $changed" >&2; exit 1; }
echo "rerecord-commit: committed $(git rev-parse HEAD) ($venues)"
