#!/usr/bin/env bash

set -euo pipefail
IFS=$'\n\t'

# --- Settings ----------------------------------------------------------------
LOGFILE="vna_protocol.bin"      # will be normalized to absolute path
DEVICE="/dev/ttyACM0"
REAL_DEV="${DEVICE}.real"
VIRT_DEV="/tmp/vna_log"         # PTY endpoint for the app (peer created by socat)

# Normalize LOGFILE and ensure directory exists
if command -v realpath >/dev/null 2>&1; then
  LOGFILE="$(realpath -m -- "$LOGFILE")"
else
  LOGFILE="$(cd "$(dirname "$LOGFILE")" && pwd -P)/$(basename "$LOGFILE")"
fi
mkdir -p "$(dirname "$LOGFILE")"

BRIDGE="./bridge_logger.py"

# --- Helpers -----------------------------------------------------------------
restore_device() {
  [[ -e "$VIRT_DEV" || -L "$VIRT_DEV" ]] && rm -f "$VIRT_DEV" || true
  if [[ -e "$DEVICE" && ! -c "$DEVICE" ]]; then rm -f "$DEVICE" || true; fi
  if [[ -e "$REAL_DEV" ]]; then sudo mv -f "$REAL_DEV" "$DEVICE" || true; fi
  if [[ -e "$REAL_DEV" && -c "$DEVICE" ]]; then rm -f "$REAL_DEV" || true; fi
}

kill_descendants() {
  pkill -TERM -P $$ 2>/dev/null || true
  sleep 0.1
  pkill -KILL -P $$ 2>/dev/null || true
}


# --- Cleanup -----------------------------------------------------------------
CLEANED=0
cleanup() {
  (( CLEANED )) && return 0
  CLEANED=1
  set +e
  echo; echo "Stopping logger..."
  restore_device
  kill_descendants
  echo "Log saved to: $LOGFILE"
  echo "Cleanup complete."
}
trap cleanup EXIT INT TERM HUP QUIT

echo "== Preparing direction-switch protocol logging =="
echo "Binary log file: $LOGFILE"

# Fix leftovers from previous run (if any)
if [[ -e "$REAL_DEV" ]]; then
  echo "Found leftover $REAL_DEV — restoring..."
  restore_device
fi

# Safety checks
[[ -e "$DEVICE" ]] || { echo "Error: device $DEVICE not found."; exit 1; }
[[ -c "$DEVICE" ]] || { echo "Error: $DEVICE is not a character device."; exit 1; }

# Park the real device and create a PTY pair for the application
sudo mv "$DEVICE" "$REAL_DEV"
socat -d -d pty,raw,echo=0,link="$DEVICE",mode=666 \
          pty,raw,echo=0,link="$VIRT_DEV" &
sleep 1

# Configure the real serial device (adjust if needed)
stty -F "$REAL_DEV" 115200 cs8 -cstopb -parenb -ixon -ixoff -crtscts raw -echo

# Initialize the binary log with a magic header (if empty)
if [[ ! -s "$LOGFILE" ]]; then
  printf 'VNALOG1\n' > "$LOGFILE"
fi

# Run the bridge+logger (single process handles both directions + logging)
"$BRIDGE" "$VIRT_DEV" "$REAL_DEV" "$LOGFILE" &

echo "Logging active. Press Ctrl+C to stop."
wait
