#!/usr/bin/env bash
# Live headless Ghidra query against an ALREADY-ANALYZED program in the
# persistent project. Drives everything from chat with zero GUI.
#
# Usage: ./re-q <program> <command> [args...]
#
#   <program>  domain-file name in ./work/ChipBenchProject (e.g. "dump.bin")
#   <command>  info | funcs | decompile | disasm | xrefs-to | xrefs-from |
#              func-xrefs | strings | segments | data | search | func | mem
#
# Examples:
#   ./re-q dump.bin info
#   ./re-q dump.bin funcs "" 500
#   ./re-q dump.bin decompile FUN_0000
#   ./re-q dump.bin decompile 0x8000
#   ./re-q dump.bin disasm 0x8000
#   ./re-q dump.bin xrefs-to 0x8000
#   ./re-q dump.bin strings init
#   ./re-q dump.bin mem 0x8000 64
set -euo pipefail
cd "$(dirname "$0")"

if [ "$#" -lt 2 ]; then
    sed -n '2,18p' "$0" >&2
    exit 2
fi
PROG="$1"; shift
# Python print() in Ghidra goes to stdout without the "Query.py>" prefix that
# Java scripts get. Filter out Ghidra's own log noise instead.
docker compose run --rm -T \
    --entrypoint /opt/ghidra/support/analyzeHeadless \
    tools \
    /data/work ChipBenchProject \
    -process "$PROG" -noanalysis -readOnly \
    -scriptPath /opt/ghidra-scripts \
    -postScript Query.py "$@" 2>&1 \
  | grep -vE "^INFO |^WARN |^ERROR |^  [A-Z]|^$|Module manifest|Picked up|openjdk|OpenJDK|RE shell|try:|Artifacts:|Project:|Container|Creat|Remov|^    /opt|^    [A-Z]" \
  | sed 's/^(//; s/)$//'  # strip Jython tuple wrapper like ('text',)
