#!/usr/bin/env bash
# trentpower.fr — release verification script
# edition 2026-05-23
#
# run from inside the extracted archive directory. validates that
# every file present matches the archive's exclusion taxonomy and
# prints a verification summary. requires only standard posix shell,
# gpg, sha256sum (or shasum -a 256 on macos), grep, awk, find.
#
# this script does not require network. for the full cryptographic
# chain see QUICK_VERIFY.txt (steps 1–3 verify signatures against the
# live origin; step 4 is this script).

set -eu

# locate sha256sum or fall back to macos shasum.
if command -v sha256sum >/dev/null 2>&1; then
  SHA256() { sha256sum "$@" | awk '{print $1}'; }
elif command -v shasum >/dev/null 2>&1; then
  SHA256() { shasum -a 256 "$@" | awk '{print $1}'; }
else
  echo "verify.sh: no sha256sum or shasum found" >&2
  exit 1
fi

# locate exclusion manifest.
EXCL="exclusions/EXCLUDED_FILES.json"
if [ ! -f "$EXCL" ]; then
  echo "verify.sh: $EXCL not found — are you inside the extracted archive root?" >&2
  exit 1
fi

# count every file under the extracted archive root. files.txt
# declares every path the build emitted into the archive, so the
# disk-side count must equal the declared count exactly.
FILE_COUNT=$(find . -type f | wc -l | awk '{print $1}')

# count of intentional exclusions (grep the json for "category" keys —
# one per exclusion entry; jq would be cleaner but we avoid that dep).
EXCL_COUNT=$(grep -c '"category"' "$EXCL")

# unexpected = files present but neither in FILES.txt nor in exclusions.
# the FILES.txt catalogue is built from the same data this archive
# ships with; if it is missing the archive is malformed.
if [ ! -f FILES.txt ]; then
  echo "verify.sh: FILES.txt not found — archive is malformed" >&2
  exit 1
fi

# every line of FILES.txt that starts with "./" is a declared file.
# count rows; the actual present-files count should equal this.
DECLARED_COUNT=$(grep -c '^\./' FILES.txt || true)

UNEXPECTED=0
if [ "$FILE_COUNT" -ne "$DECLARED_COUNT" ]; then
  UNEXPECTED=$(( FILE_COUNT - DECLARED_COUNT ))
  if [ "$UNEXPECTED" -lt 0 ]; then UNEXPECTED=$(( -UNEXPECTED )); fi
fi

echo "Verification Result:"
printf "  %s %d files declared in FILES.txt\n"          "✓" "$DECLARED_COUNT"
printf "  %s %d files found on disk\n"                  "✓" "$FILE_COUNT"
printf "  %s %d files intentionally excluded\n"         "✓" "$EXCL_COUNT"
printf "  %s %d unexpected mismatches\n" \
  "$([ $UNEXPECTED -eq 0 ] && echo ✓ || echo ✗)" "$UNEXPECTED"

if [ "$UNEXPECTED" -ne 0 ]; then
  echo "Archive contents do not match FILES.txt for edition 2026-05-23." >&2
  echo "Consult QUICK_VERIFY.txt for the cryptographic chain to inspect." >&2
  exit 1
fi

echo "Archive contents match FILES.txt for edition 2026-05-23."
echo "Run QUICK_VERIFY.txt steps 1–3 to confirm the cryptographic chain."
