#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

IDA_BIN="${IDA_BIN:-/home/HOME/software/IDA-Pro/idat}"
DUMP_SCRIPT="${REPO_ROOT}/scripts/dump_pseudo.py"

if [[ ! -x "${IDA_BIN}" ]]; then
  echo "error: IDA binary not found or not executable at ${IDA_BIN}" >&2
  exit 1
fi

if [[ ! -f "${DUMP_SCRIPT}" ]]; then
  echo "error: dump script not found at ${DUMP_SCRIPT}" >&2
  exit 1
fi

readarray -t BINARIES < <(
  find "${REPO_ROOT}" -mindepth 2 -maxdepth 2 -type f \
    \( -iname '*.o0' -o -iname '*.o1' -o -iname '*.o2' -o -iname '*.o3' \) \
    ! -path "${REPO_ROOT}/scripts/*" \
    ! -path "${REPO_ROOT}/target/*" \
    ! -path "${REPO_ROOT}/common/*" \
    ! -path "${REPO_ROOT}/.git/*" \
    | sort
)

if [[ ${#BINARIES[@]} -eq 0 ]]; then
  echo "error: no O0/O1/O2/O3 binaries found under ${REPO_ROOT}" >&2
  exit 1
fi

for binary_path in "${BINARIES[@]}"; do
  output_path="${binary_path}.pseudo"
  echo "==> Decompiling ${binary_path#${REPO_ROOT}/} -> ${output_path#${REPO_ROOT}/}"
  "${IDA_BIN}" -A "-S${DUMP_SCRIPT} ${output_path}" "${binary_path}"
done

echo "All pseudocode dumps are located alongside their binaries."
