#!/usr/bin/env bash
# launch-vnc-viewer.sh — Launch a VNC viewer for a libvirt domain.
#
# Usage: bash launch-vnc-viewer.sh <domain> <vnc_display>
# Example: bash launch-vnc-viewer.sh sc-web-server :0
#
# Tries: virt-viewer → vncviewer → xtightvncviewer → vinagre (in order)
# Exits 1 if none found.

DOMAIN="${1:-}"
VNC_DISPLAY="${2:-:0}"

# Convert :N display to port 5900+N
PORT=$((5900 + ${VNC_DISPLAY#:}))
HOST="127.0.0.1"

if command -v virt-viewer &>/dev/null; then
    exec virt-viewer --connect qemu:///session "$DOMAIN"
elif command -v vncviewer &>/dev/null; then
    exec vncviewer "${HOST}:${PORT}"
elif command -v xtightvncviewer &>/dev/null; then
    exec xtightvncviewer "${HOST}:${PORT}"
elif command -v vinagre &>/dev/null; then
    exec vinagre "vnc://${HOST}:${PORT}"
else
    echo "ERROR: No VNC viewer found. Install virt-viewer or vncviewer." >&2
    exit 1
fi
