#!/usr/bin/env bash
set -euo pipefail
BUNDLE="${1:-$HOME/Downloads/Braid-Trust.braidtrust}"
BRAID_HOME="${BRAID_HOME:-$HOME/.braid}"
TRUST_DIR="$BRAID_HOME/trust"
BRAID_BIN="${BRAID_BIN:-$HOME/.local/bin/braid-client}"
[[ -f "$BUNDLE" ]] || { echo "Braid Trust bundle not found: $BUNDLE" >&2; exit 1; }
[[ -x "$BRAID_BIN" ]] || { echo "Braid CLI not found at $BRAID_BIN" >&2; exit 1; }
TMP="$(mktemp -d)"
STAGE="$BRAID_HOME/.trust-stage.$$"
trap 'rm -rf "$TMP" "$STAGE"' EXIT

python3 - "$BUNDLE" <<'PY2'
import sys, tarfile
p=sys.argv[1]
with tarfile.open(p, 'r:gz') as t:
    names=[]
    for m in t.getmembers():
        parts=m.name.split('/')
        if m.name.startswith('/') or '..' in parts or m.issym() or m.islnk() or m.isdev():
            raise SystemExit(f"Unsafe Braid Trust member: {m.name}")
        if any(part == 'sender.key' for part in parts):
            raise SystemExit("Braid Trust bundle illegally contains sender.key")
        names.append(m.name)
    new = 'Braid-Trust/trust.json' in names
    old = 'Braid-Pairing/pairing.json' in names
    if not (new or old):
        raise SystemExit("Braid Trust metadata missing")
    if new and old:
        raise SystemExit("Ambiguous bundle contains both trust and legacy pairing roots")
PY2

tar -xzf "$BUNDLE" -C "$TMP"
if [[ -d "$TMP/Braid-Trust" ]]; then
  SRC="$TMP/Braid-Trust"
  META="$SRC/trust.json"
  python3 - "$META" <<'PY2'
import json,sys
p=json.load(open(sys.argv[1]))
if p.get('schema') != 'braid.trust-bundle.v1': raise SystemExit('Unsupported Braid Trust schema')
if p.get('version') != '1.5.2': raise SystemExit('Braid Trust version mismatch')
if p.get('private_key_included') is not False: raise SystemExit('Unsafe Braid Trust metadata')
if not isinstance(p.get('embed_model'), str) or not p['embed_model']: raise SystemExit('Missing embed_model')
PY2
else
  # Backward-compatible import of RC1/Hotfix pairing bundles.
  SRC="$TMP/Braid-Pairing"
  META="$SRC/pairing.json"
  python3 - "$META" <<'PY2'
import json,sys
p=json.load(open(sys.argv[1]))
if p.get('schema') != 'braid.pairing-bundle.v1': raise SystemExit('Unsupported legacy pairing schema')
if p.get('version') != '1.5.2': raise SystemExit('Legacy pairing version mismatch')
if p.get('private_key_included') is not False: raise SystemExit('Unsafe legacy pairing metadata')
if not isinstance(p.get('embed_model'), str) or not p['embed_model']: raise SystemExit('Missing embed_model')
PY2
fi

[[ -f "$SRC/sender.pub" && -f "$SRC/source-route/route.json" && -f "$META" ]] || { echo "Invalid Braid Trust bundle." >&2; exit 1; }
if [[ -f "$SRC/SHA256SUMS.txt" ]]; then
  ( cd "$SRC" && sha256sum -c SHA256SUMS.txt >/dev/null )
fi
"$BRAID_BIN" hetero-route-info "$SRC/source-route" >/dev/null

mkdir -p "$BRAID_HOME" "$STAGE/source-route"
cp -a "$SRC/source-route/." "$STAGE/source-route/"
cp "$SRC/sender.pub" "$STAGE/sender.pub"
python3 - "$META" "$STAGE/trust.json" <<'PY2'
import json,sys
p=json.load(open(sys.argv[1]))
out={
  'schema':'braid.trust-bundle.v1',
  'version':'1.5.2',
  'embed_model':p['embed_model'],
  'private_key_included':False,
  'scope':'authorized-signer-route',
}
if p.get('schema') == 'braid.pairing-bundle.v1': out['migration']='legacy-pairing-bundle-v1'
json.dump(out, open(sys.argv[2],'w'), separators=(',',':'))
PY2
chmod 0644 "$STAGE/sender.pub" "$STAGE/trust.json"
rm -rf "$TRUST_DIR"
mv "$STAGE" "$TRUST_DIR"
trap 'rm -rf "$TMP"' EXIT

echo "Braid Trust enrolled into $TRUST_DIR"
echo "Route verified; sender private key was not imported."
echo "Double-click Braid Client or run: braid-receiver"
