#!/usr/bin/env bash
# Integrity check, safe to run on the offline target before installing.
# Confirms nothing was lost or altered in transit.
set -uo pipefail
BUNDLE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$BUNDLE"
PY="$(command -v python3.12 || command -v python3)"
rc=0

echo "==> checksums"
if [[ -f MANIFEST.sha256 ]]; then
  if out="$(sha256sum -c --quiet MANIFEST.sha256 2>&1)"; then
    echo "    OK  $(wc -l < MANIFEST.sha256) files match"
  else
    echo "    FAILED:"; echo "$out" | sed 's/^/      /'; rc=1
  fi
else
  echo "    MANIFEST.sha256 missing"; rc=1
fi

echo "==> wheel coverage vs lock files"
# Compared in Python so that names are matched the way pip matches them
# (PEP 503: case-insensitive, with -, _ and . all equivalent). Some projects
# still publish legacy mixed-case filenames, e.g. MarkupSafe-2.1.5-*.whl.
"$PY" - <<'PY' || rc=1
import pathlib, re, sys

def norm(s):
    return re.sub(r"[-_.]+", "-", s).lower()

bad = False
for tag in ("py39", "py312"):
    lock = pathlib.Path(f"requirements/gradio-{tag}.lock.txt")
    have = {}
    for f in pathlib.Path(f"wheels/{tag}").glob("*.whl"):
        name, ver = f.name.split("-")[0], f.name.split("-")[1]
        have.setdefault(norm(name), set()).add(ver)
    want = [l.split("==") for l in lock.read_text().split()
            if l and not l.startswith("#")]
    missing = [f"{n}=={v}" for n, v in want if v not in have.get(norm(n), ())]
    if missing:
        bad = True
        for m in missing:
            print(f"    MISSING wheel: {m}")
    else:
        print(f"    OK  {tag}: all {len(want)} packages present")
sys.exit(1 if bad else 0)
PY

echo "==> no source archives in the wheel directories"
if find wheels -name '*.tar.gz' -o -name '*.zip' | grep -q .; then
  echo "    WARNING: source archives found under wheels/; these would need a"
  echo "    compiler on this host. They belong in sdists/."
  rc=1
else
  echo "    OK  wheels/ contains only .whl files"
fi

echo "==> interpreters on this host"
for p in python3.9 python3.12; do
  if command -v "$p" >/dev/null 2>&1; then
    echo "    OK  $p -> $($p -V 2>&1)"
  else
    echo "    absent: $p  (see docs/PREREQUISITES.md)"
  fi
done

echo
[[ $rc == 0 ]] && echo "bundle looks intact" || echo "PROBLEMS FOUND (see above)"
exit $rc
