#!/usr/bin/env bash
# rollback_beebo_catalog.sh <UI_DIR>
#
# Deterministic revert of apply_beebo_catalog.py: verifies the current
# module_info.py is byte-exactly the file recorded at apply time, restores
# module_info.py.orig over it, and verifies the restored hash. Keeps the
# .orig file on disk for the audit trail.
set -eu

[ "${1:-}" != "" ] || { echo "usage: $0 <UI_DIR containing module_info.py>" >&2; exit 2; }
UI="$1"
MI="$UI/module_info.py"
ORIG="$UI/module_info.py.orig"
STATE="$UI/.beebo_catalog_state.json"

[ -f "$STATE" ] || { echo "error: $STATE not found - nothing to roll back" >&2; exit 1; }
[ -f "$ORIG" ]  || { echo "error: $ORIG not found" >&2; exit 1; }
[ -f "$MI" ]    || { echo "error: $MI not found" >&2; exit 1; }

CUR="$(sha256sum "$MI" | cut -d' ' -f1)"
REC_PATCHED="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["patched_sha256"])' "$STATE")"
[ "$CUR" = "$REC_PATCHED" ] || { echo "error: module_info.py differs from the recorded patched file; refusing" >&2; exit 1; }

cp -p "$ORIG" "$MI"
NOW="$(sha256sum "$MI" | cut -d' ' -f1)"
REC_ORIG="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["original_sha256"])' "$STATE")"
[ "$NOW" = "$REC_ORIG" ] || { echo "FATAL: restored hash mismatch" >&2; exit 1; }
echo "module_info.py restored to stock ($NOW) — catalog rollback complete"