#!/usr/bin/env bash
# launch-spice-viewer.sh — Launch a SPICE viewer for a libvirt domain.
#
# Usage: bash launch-spice-viewer.sh <domain> [vnc_display_fallback]

DOMAIN="${1:-}"
LIBVIRT_URI="${LIBVIRT_DEFAULT_URI:-qemu:///system}"

if command -v virt-viewer &>/dev/null; then
    exec virt-viewer --connect "$LIBVIRT_URI" "$DOMAIN"
elif command -v remote-viewer &>/dev/null; then
    # Get SPICE port from virsh
    SPICE_URI=$(virsh --connect "$LIBVIRT_URI" domdisplay "$DOMAIN" 2>/dev/null | grep spice | head -1)
    if [ -n "$SPICE_URI" ]; then
        exec remote-viewer "$SPICE_URI"
    else
        echo "ERROR: No SPICE display found for $DOMAIN" >&2
        exit 1
    fi
elif command -v spicy &>/dev/null; then
    SPICE_PORT=$(virsh --connect "$LIBVIRT_URI" domdisplay "$DOMAIN" 2>/dev/null | grep -oP '(?<=:)\d+' | head -1)
    exec spicy -h 127.0.0.1 -p "${SPICE_PORT:-5900}"
else
    echo "ERROR: No SPICE viewer found. Install virt-viewer." >&2
    exit 1
fi
