#!/usr/bin/env bash
# The vendored BW kit must be byte-identical to its source (plan accounts-2026-09 §4.1).
# Against the kit when it exists on this machine, against MANIFEST.sha256 when it does not
# (a transferred codebase has no kit), so a hand edit fails check.sh either way. A vendored
# copy on this server had already drifted from its kit unnoticed: "never hand-edited" needs
# a check, not a promise. scripts/vendor-refresh.sh is the only sanctioned way these change.
set -euo pipefail
cd "$(dirname "$0")/.."
KIT=/srv/system/id-auth/app-auth
MANIFEST=app/vendor/MANIFEST.sha256
fail=0
if [[ -d "$KIT" ]]; then
  while read -r sum path; do
    case "$path" in
      app/vendor/*.py) src="$KIT/${path#app/vendor/}";;
      web/src/vendor/bw-admin/*) src="$KIT/react-admin/${path#web/src/vendor/bw-admin/}";;
      tests/kit/test_*.py) src="$KIT/app-template/main/tests/${path#tests/kit/}";;
      *) echo "vendor-check: unexpected manifest path $path"; fail=1; continue;;
    esac
    if [[ ! -f "$src" ]]; then echo "vendor-check: no kit source for $path"; fail=1; continue; fi
    if ! cmp -s "$src" "$path"; then echo "vendor-check: $path differs from $src"; fail=1; fi
  done < "$MANIFEST"
fi
if ! sha256sum --quiet -c "$MANIFEST" >/dev/null 2>&1; then
  sha256sum -c "$MANIFEST" | grep -v ': OK$' || true; fail=1
fi
# A vendored file the manifest does not list is as bad as a changed one.
for f in app/vendor/*.py web/src/vendor/bw-admin/* tests/kit/test_*.py; do
  [[ -e "$f" ]] || continue
  case "$f" in app/vendor/__init__.py) continue;; esac
  grep -q " $f\$" "$MANIFEST" || { echo "vendor-check: $f is not in $MANIFEST"; fail=1; }
done

# The second manifest: the caddie-ui pack (accounts plan §8), stamped by the pack's own script
# (`/srv/apps/caddie/packs/stamp-caddie-ui.sh <workspace> --src-dir main/web/src/vendor`) and
# checked against its canonical copy when that workspace exists, else against the manifest.
PACK=/srv/apps/caddie/packs/caddie-ui
PACK_MANIFEST=web/src/vendor/MANIFEST-caddie-ui.sha256
if [[ -f "$PACK_MANIFEST" ]]; then
  if [[ -d "$PACK" ]]; then
    while read -r sum path; do
      src="$PACK/${path#web/src/vendor/caddie-ui/}"
      if [[ ! -f "$src" ]]; then echo "vendor-check: no pack source for $path"; fail=1; continue; fi
      if ! cmp -s "$src" "$path"; then echo "vendor-check: $path differs from $src"; fail=1; fi
    done < "$PACK_MANIFEST"
  fi
  if ! sha256sum --quiet -c "$PACK_MANIFEST" >/dev/null 2>&1; then
    sha256sum -c "$PACK_MANIFEST" | grep -v ': OK$' || true; fail=1
  fi
  for f in web/src/vendor/caddie-ui/*; do
    [[ -e "$f" ]] || continue
    grep -q " $f\$" "$PACK_MANIFEST" || { echo "vendor-check: $f is not in $PACK_MANIFEST"; fail=1; }
  done
fi
if (( fail )); then echo "vendor-check: FAILED (refresh with scripts/vendor-refresh.sh; never hand-edit)"; exit 1; fi
echo "vendor-check: ok"
