#!/bin/sh
# DF-5732 live-pass rig — guest with a WRITABLE socket serial console
# (adapted verbatim from the proven DF-5728/DF-5721 rigs). Same disk/net/
# kvm/pidfile as vm.sh so vm.sh keeps managing the guest.
#
# Usage: serial_vm.sh up|down|status|log [n]
set -eu
cd "$(dirname "$0")/../../../dfbsd-qemu"

DISK="disk.qcow2"
PIDFILE="vm.pid"
BOOTLOG="boot.log.df5732-ddb"
SOCK="/tmp/opencode/df-5732-ser.sock"
SSH_OPTS="-F config -o ConnectTimeout=8 -o BatchMode=yes"

status_up() { ssh $SSH_OPTS dfbsd-maxx true >/dev/null 2>&1; }

case "${1:-}" in
up)
    if status_up; then echo "already up"; exit 0; fi
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE" 2>/dev/null)" 2>/dev/null; then
        echo "qemu already running (pid $(cat "$PIDFILE"))" >&2; exit 1
    fi
    rm -f "$PIDFILE" "$SOCK"; : > "$BOOTLOG"
    echo "booting guest with socket serial: $SOCK (log: $BOOTLOG)"
    qemu-system-x86_64 \
        -enable-kvm -m 4096 -smp 6 \
        -drive file="$DISK",if=virtio,format=qcow2 \
        -netdev user,id=n0,hostfwd=tcp:127.0.0.1:5522-:22 \
        -device virtio-net-pci,netdev=n0 \
        -display none -monitor unix:"boot-mon.sock",server,nowait \
        -chardev socket,id=ser0,path="$SOCK",server=on,wait=off,logfile="$BOOTLOG" \
        -serial chardev:ser0 \
        -daemonize -pidfile "$PIDFILE"
    echo "waiting for ssh..."
    i=0; while [ $i -lt 150 ]; do
        if status_up; then echo "up (pid $(cat "$PIDFILE"))"; exit 0; fi
        sleep 3; i=$((i+3))
    done
    echo "TIMEOUT waiting for ssh; tail $BOOTLOG" >&2; exit 1
    ;;
down)
    ./vm.sh down || true
    ;;
status)
    if status_up; then echo up; else echo down; fi
    ;;
log)
    tail -n "${2:-60}" "$BOOTLOG" 2>/dev/null || echo "no $BOOTLOG"
    ;;
*) echo "usage: $0 up|down|status|log [n]" >&2; exit 2 ;;
esac
