#!/usr/bin/env bash
# Rebuild every reverse-engineering output from work/slices/ (run scripts/bootstrap first):
# the names files, a clean headless Ghidra project with all names applied, and the generated
# docs in docs/re/ that depend on the Ghidra export. The order matters:
#
#   1. names generators (work/re/names/*.json). flow runs last: it skips addresses that the
#      other names files already cover.
#   2. tools/ghidra/import: a clean project; applies every names file, then exports
#      work/ghidra/{functions,xrefs,strings}.json (deterministic, ADR 0007).
#   3. libtags (#10): reads the export, writes work/re/function-tags.json and its doc.
#   4. Ghidra scripts on the project: apply_tags.py puts those tags on the functions and reads
#      them back into work/re/ghidra-tags.json; pngdat_calls.py writes the pack-loader call
#      listing work/re/pngdat_calls.txt (#17). Neither re-exports, and neither changes what an
#      export would contain (a reexport afterwards is byte-identical), so the export written
#      by step 2 stays the canonical input of the generated docs.
#   5. generators that read the export: imports (#11), objcshell (#22, which also needs
#      the tags and the extracted bundle) and audio (#29, the bundle's sound/ and map/ files).
#
# Afterwards `git status` shows any generated doc that was stale; commit those mechanically.
# Environment: MAPLETHIEF_DOWNLOAD_DIR / MAPLETHIEF_GHIDRA_DIR as in tools/ghidra/README.md;
# PYTHON=<interpreter> overrides python3 (needs 3.10+).
set -euo pipefail

REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$REPO"
PY="${PYTHON:-python3}"
export PYTHONPATH="$REPO/tools${PYTHONPATH:+:$PYTHONPATH}"

run() { echo "+ $*" >&2; "$@"; }

run "$PY" -B -m mtport.objc generate
run "$PY" -B -m mtport.rtti generate
for module in savedata scriptout network timing objcshell audio autosave screenshake flashes hudextras mechanics scenes compendium.world flow; do
  run "$PY" -B -m "mtport.$module" names
done
run tools/ghidra/import
generate() { run uv run --locked --group tools python -B -m "mtport.$1" generate; }
generate libtags
run tools/ghidra/run-script apply_tags.py
run tools/ghidra/run-script pngdat_calls.py work/re/pngdat_calls.txt
for module in imports objcshell audio; do
  generate "$module"
done
