#!/usr/bin/env bash
# verify-x68000-serial.sh - both-directions RS-232C gate for the X68000 port.
#
# Boots SERIAL.X under the patched MAME with SCC channel A wired to a null_modem
# on a TCP socket, sends a probe string in, and checks the example echoes it
# back. That exercises the full chain: elf2x68k -> .X -> xdftool image ->
# Human68k -> JoeyLib serial HAL -> IOCS -> SCC -> host.
#
# Requires: the patched MAME built at toolchains/cache/mame-mame0264/x68k
#           (patches/mame-0.264-x68k-rs232.patch), and a Human68k template
#           image to copy.
set -uo pipefail

repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
SP="${X68K_SCRATCH:?set X68K_SCRATCH to a work dir containing x68mame/}"
MAME="$repo/toolchains/cache/mame-mame0264/x68k"
TEMPLATE="$SP/x68mame/HUMAN302.XDF"
ROMS="$SP/x68mame/roms"
PORT="${X68K_SERIAL_PORT:-6800}"
PROBE="${X68K_SERIAL_PROBE:-JOEYLIB-X68K}"
MAXWAIT="${X68K_SERIAL_TIMEOUT:-420}"

for f in "$MAME" "$TEMPLATE"; do
    [ -e "$f" ] || { echo "verify-x68000-serial: missing $f" >&2; exit 2; }
done

work=$(mktemp -d -t joey-x68ser.XXXXXX)
trap 'rm -rf "$work"; kill %1 2>/dev/null' EXIT

# Autorun SERIAL.X. No ECHO OFF so a load failure is visible in a screenshot.
printf 'A:\\SERIAL.X\r\n\x1a' > "$work/AUTOEXEC.BAT"
cp "$TEMPLATE" "$work/serial.xdf"
python3 "$repo/tools/xdftool.py" add "$work/serial.xdf" \
        "$repo/build/x68000/bin/SERIAL.X" SERIAL.X >/dev/null
python3 "$repo/tools/xdftool.py" add "$work/serial.xdf" \
        "$work/AUTOEXEC.BAT" AUTOEXEC.BAT >/dev/null

# Host end of the link. MAME's null_modem socket form CONNECTS, so we listen.
python3 "$repo/scripts/x68kSerialPeer.py" \
        --port "$PORT" --probe "$PROBE" --timeout "$MAXWAIT" \
        > "$work/peer.out" 2>&1 &
peer=$!
sleep 2

timeout -s KILL "$MAXWAIT" "$MAME" x68000 \
    -bios ipl10 -rompath "$ROMS" \
    -flop1 "$work/serial.xdf" \
    -rs232c null_modem -bitb "socket.127.0.0.1:$PORT" \
    -video none -sound none -nothrottle </dev/null >/dev/null 2>&1

wait "$peer"
rc=$?
cat "$work/peer.out"
exit $rc
