#!/usr/bin/env bash
# usage: dump.sh <dotted.path> [outname]
set -u
TOK=giTacehU47nEagp4IsK6lxJbXWxb7bXVv-Q05Bg4ybc
P="$1"
OUT="${2:-$1}"
OUTFILE="/opt/ws-remote/scripts/admin/72169370437173/dump/${OUT}.lua"
mkdir -p "$(dirname "$OUTFILE")"
python3 /opt/ws-remote/relayctl.py --token "$TOK" --json source "$P" > "${OUTFILE}.json" 2>"${OUTFILE}.err"
python3 - "$OUTFILE" <<'PY'
import json,sys
base=sys.argv[1]
raw=open(base+".json",encoding="utf-8").read()
try:
    d=json.loads(raw)
    src=d.get("source")
    if src is None:
        open(base,"w").write("/* NO SOURCE FIELD */\n"+raw)
        print("NOSOURCE",base,d.get("class"),d.get("name"),d.get("method"))
    else:
        open(base,"w").write(src)
        print("OK",base,len(src))
except Exception as e:
    open(base,"w").write("/* JSON PARSE FAIL: "+str(e)+" */\n"+raw)
    print("PARSEFAIL",base,e)
PY
rm -f "${OUTFILE}.json"
