#!/usr/bin/env bash
# Regenerate the lock files, refresh sdists (needs network), and write
# MANIFEST.sha256. Run on the build host, not the offline target.
#
#   scripts/make-manifest.sh              # locks + checksums only
#   scripts/make-manifest.sh --sdists     # also refetch sources from PyPI
set -euo pipefail
BUNDLE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$BUNDLE"
PY="$(command -v python3.12 || command -v python3)"

echo "==> regenerating lock files from wheels/"
for tag in py39 py312; do
  "$PY" - "wheels/$tag" > "requirements/gradio-$tag.lock.txt" <<'PY'
import sys, pathlib
n = {(f.name.split('-')[0].replace('_', '-').lower(), f.name.split('-')[1])
     for f in pathlib.Path(sys.argv[1]).glob('*.whl')}
for k, v in sorted(n):
    print(f"{k}=={v}")
PY
  echo "    requirements/gradio-$tag.lock.txt  ($(wc -l < "requirements/gradio-$tag.lock.txt") packages)"
done

if [[ "${1:-}" == "--sdists" ]]; then
  echo "==> refreshing sdists from PyPI (network required)"
  for tag in py39 py312; do
    "$PY" scripts/fetch-sdists.py "requirements/gradio-$tag.lock.txt" "sdists/$tag"
  done
fi

echo "==> writing MANIFEST.sha256"
find bootstrap wheels sdists templates scripts requirements docs \
     -type f ! -name '*.pyc' -print0 \
  | sort -z | xargs -0 sha256sum > MANIFEST.sha256
sha256sum gradio-offline.env README.md INSTALL.md >> MANIFEST.sha256
echo "    $(wc -l < MANIFEST.sha256) files"

echo "==> summary"
printf '    wheels/py39   %3d wheels  %s\n' "$(ls wheels/py39 | wc -l)"   "$(du -sh wheels/py39   | cut -f1)"
printf '    wheels/py312  %3d wheels  %s\n' "$(ls wheels/py312 | wc -l)"  "$(du -sh wheels/py312  | cut -f1)"
printf '    sdists/py39   %3d files   %s\n' "$(ls sdists/py39 | wc -l)"   "$(du -sh sdists/py39   | cut -f1)"
printf '    sdists/py312  %3d files   %s\n' "$(ls sdists/py312 | wc -l)"  "$(du -sh sdists/py312  | cut -f1)"
