#!/usr/bin/env bash
# P3 USG menu (?), GAMESTATS sanity, TARGAFILE / TGALN VRAM capture.
#
# Office Pi (topbox5 @ 10.1.10.140) or any Pi with P3 on /dev/ttyUSB0 @ 115200 8N1.
# Stop DyzineFrame before running (it holds ttyUSB0).
#
# Usage:
#   ./run_p3_usg_probe.sh menu
#   ./run_p3_usg_probe.sh gamestats
#   ./run_p3_usg_probe.sh targa --out /tmp/keno_help.tga
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TOOLS="${SCRIPT_DIR}/tools"
export P3_SERIAL_PORT="${P3_SERIAL_PORT:-/dev/ttyUSB0}"

echo "=== P3 USG probe port=${P3_SERIAL_PORT} ==="

if [[ ! -e "${P3_SERIAL_PORT}" ]]; then
  echo "WARN: ${P3_SERIAL_PORT} not found" >&2
  ls /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || true
fi

if command -v fuser >/dev/null 2>&1; then
  if fuser -s "${P3_SERIAL_PORT}" 2>/dev/null; then
    echo "WARN: another process holds ${P3_SERIAL_PORT}:" >&2
    fuser -v "${P3_SERIAL_PORT}" 2>/dev/null || true
  fi
fi

exec python3 "${TOOLS}/p3_usg_probe.py" "$@"
