#!/usr/bin/env bash
# Headless Ghidra import + auto-analysis + full export.
#
# Usage:
#   ./re-analyze <file-in-artifacts> [analyzeHeadless options...]
#
# Let Ghidra auto-detect the architecture, or force it with -processor:
#   ./re-analyze dump.bin -processor "8051:BE:16:default"     # Intel 8051
#   ./re-analyze dump.bin -processor "AVR8:LE:16:default"     # Atmel AVR
#   ./re-analyze dump.bin -processor "PIC-16:BE:16:PIC-16F"   # PIC16F
#   ./re-analyze dump.bin -processor "PIC-18:LE:16:PIC-18F"   # PIC18F
#   ./re-analyze dump.bin -processor "PIC-24:LE:24:default"   # PIC24/dsPIC
#   ./re-analyze dump.bin -processor "STM8:BE:8:default"      # ST STM8
#   ./re-analyze dump.bin -processor "6502:LE:16:default"     # MOS 6502/6507
#   ./re-analyze dump.bin -processor "Z80:BE:16:default"      # Zilog Z80/Z180
#   ./re-analyze dump.bin -processor "HC08:BE:16:default"     # Freescale HC(S)08
#   ./re-analyze dump.bin -processor "RL78:LE:16:default"     # Renesas RL78
#
# Raw binary imports have no symbols: 8051-family dumps additionally get
# vector + sweep disassembly via Analyze8051.py (skipped for other archs,
# or force-skip for 8051 with RE_NO_SWEEP=1).
set -euo pipefail
cd "$(dirname "$0")"

if [ "$#" -lt 1 ]; then
    echo "usage: $0 <file-in-artifacts> [analyzeHeadless options...]" >&2
    exit 2
fi

ARTIFACT="$1"; shift

POST=(-postScript ExportAll.py)
if [ -z "${RE_NO_SWEEP:-}" ] && grep -qi '8051' <<<" $* "; then
    POST=(-postScript Analyze8051.py "${POST[@]}")
fi

exec docker compose run --rm -T \
    --entrypoint /opt/ghidra/support/analyzeHeadless \
    tools \
    /data/work ChipBenchProject \
    -import "/data/artifacts/${ARTIFACT}" \
    -overwrite \
    "$@" \
    -scriptPath /opt/ghidra-scripts \
    "${POST[@]}"
