#!/usr/bin/env bash
# Ground-truth HS edge logger — Pi GPIO tap on SLV_HS (see HS_GPIO_TAP.md).
#
# Runs in the FOREGROUND alongside the bridge. It only reads a GPIO line, so it
# does not touch /dev/ttyXRUSB*, the uartd socket, or the wire path.
#
# START THIS AFTER THE BRIDGE. Bridge launchers default to CLEAR_CAPTURE=1, which
# wipes data/ at startup. Logger-first meant the bridge unlinked
# hs_gpio_machine.jsonl out from under this process's open fd: the console kept
# counting edges and printed a healthy total, but the name was gone, so ls and
# rclone never saw it. Both sides are hardened now (wipe preserves hs_gpio*, the
# writer reopens an unlinked path) — bridge-first is still the correct order.
#
# Usage (pos5 bench, second terminal after the bridge is up):
#   ./run_hs_gpio_logger.sh
#   HS_GPIO_LINE=11 ./run_hs_gpio_logger.sh
#
# Line number comes from hs_gpio.env (pos5 J19 currently lands on GPIO3) so a
# mistyped inline assignment cannot silently fall back to the GPIO9 default.
#
# Ctrl-C to stop. Output lands beside events.jsonl so archive_session.ps1
# picks it up with the rest of the capture.
#
# Check the line is free first:  pinctrl get 3      (or: gpioinfo)

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${ROOT}"

if [[ -f "${ROOT}/../sync/source_ethergold_env.sh" ]]; then
  # shellcheck disable=SC1091
  # shellcheck source=/dev/null
  source "${ROOT}/../sync/source_ethergold_env.sh" || true
fi

# Bench tap defaults live in a file, not a fragile one-shot command line.
# /etc wins for a seat-specific override; the checked-in dev file documents
# the current pos5 J19 landing (GPIO3).
for HS_GPIO_ENV_FILE in \
  /etc/ethergold/hs_gpio.env \
  "${ROOT}/hs_gpio.env"; do
  if [[ -f "${HS_GPIO_ENV_FILE}" ]]; then
    # shellcheck disable=SC1090
    source "${HS_GPIO_ENV_FILE}"
    break
  fi
done

HS_GPIO_LINE="${HS_GPIO_LINE:-9}"
HS_GPIO_SIGNAL="${HS_GPIO_SIGNAL:-SLV_HS}"

if [[ ! "${HS_GPIO_LINE}" =~ ^[0-9]+$ ]]; then
  echo "FATAL: HS_GPIO_LINE must be a GPIO line number, got '${HS_GPIO_LINE}'" >&2
  exit 2
fi

export OUTPUT_DIR="${OUTPUT_DIR:-${ROOT}/data}"
mkdir -p "${OUTPUT_DIR}"

if [[ ! -w "${OUTPUT_DIR}" ]]; then
  echo "FATAL: cannot write ${OUTPUT_DIR} (often root-owned after a sudo pull)" >&2
  echo "  sudo chown -R \"\$(id -un):\$(id -gn)\" \"${OUTPUT_DIR}\"" >&2
  exit 1
fi

if [[ ! -e /dev/gpiochip0 ]]; then
  echo "FATAL: no /dev/gpiochip0 — GPIO character device unavailable" >&2
  exit 1
fi

if ! python3 -c 'import fcntl' >/dev/null 2>&1; then
  echo "FATAL: python3 lacks fcntl (not a Linux python?)" >&2
  exit 1
fi

echo "hs_gpio_logger: pos=${FIXTURE_POS:-0} line=${HS_GPIO_LINE} signal=${HS_GPIO_SIGNAL}"
echo "  data -> ${OUTPUT_DIR}/hs_gpio_machine.jsonl"

exec python3 "${ROOT}/hs_gpio_logger.py" \
  --line "${HS_GPIO_LINE}" \
  --signal-name "${HS_GPIO_SIGNAL}" \
  --output-dir "${OUTPUT_DIR}" \
  --fixture-pos "${FIXTURE_POS:-0}" \
  "$@"
