#!/usr/bin/env bash
# 20260519 ChatGPT
# $Header$
#
# Example:
#   chmod 755 monitor_tbeam_with_epoch.sh
#   ./monitor_tbeam_with_epoch.sh AMY
#   ./monitor_tbeam_with_epoch.sh BOB
#   ./monitor_tbeam_with_epoch.sh CY
#
# Optional:
#   BAUD=115200 EXERCISE=305 ./monitor_tbeam_with_epoch.sh AMY

ORIG_STTY=$(stty -g)

set -euo pipefail

BOARD="${1:-AMY}"
BAUD="${BAUD:-115200}"
EXERCISE="${EXERCISE:-305}"

PORT="/dev/ttyt${BOARD}"

TS=$(date +%Y%m%d_%H%M%S)
LOGDIR="$HOME/logs/tbeam_exercise_${EXERCISE}"
LOGFILE="${LOGDIR}/${TS}_${BOARD}_exercise_${EXERCISE}_serial.log"

mkdir -p "$LOGDIR"

if [ ! -e "$PORT" ]; then
    echo "ERROR: serial device does not exist: $PORT" >&2
    exit 1
fi

CMD="pio device monitor -p ${PORT} -b ${BAUD}"
cleanup() {
    stty "$ORIG_STTY" 2>/dev/null || stty sane 2>/dev/null || true
    echo
    echo "# Terminal settings restored."
}

trap cleanup EXIT INT TERM HUP

{
    echo "# Started: $(date)"
    echo "# Epoch start: $(perl -MTime::HiRes=time -e 'printf "%.4f\n", time')"
    echo "# Host: $(hostname)"
    echo "# Board: ${BOARD}"
    echo "# Port: ${PORT}"
    echo "# Baud: ${BAUD}"
    echo "# Exercise: ${EXERCISE}"
    echo "# Command: ${CMD}"
    echo "# Logfile: ${LOGFILE}"
    echo "# ---- serial output follows ----"
} | tee "$LOGFILE"

${CMD} 2>&1 \
    | perl -MTime::HiRes=time -ne '$|=1; printf "[%.4f] %s", time, $_' \
    | tee -a "$LOGFILE"
