#!/bin/bash

if [ $# -ne 2 ]; then
    echo "Usage: $0 host domain" >&2
    exit 2
fi

host=$1
domain=$2

port=$(ssh "$host" xm list --long "$domain" | sed -n 's/^ *(location localhost:\(.*\))$/\1/ p')
if [ -z "$port" ]; then
    echo "Domain $2 not found on $1." >&2
    exit 1
fi

TMPFIFO=$(mktemp -ut "bipipe.$$.XXXXXXXXXX") || exit $?
mkfifo "$TMPFIFO" || exit $?
trap 'rm -f "$TMPFIFO"' EXIT
<"$TMPFIFO" ssh -L "$port":localhost:"$port" "$host" 'echo moo; read moo' | (
	while read -r x && [ "$x" != "moo" ]; do echo "$x"; done
	if type vinagre >/dev/null 2>&1; then
	    vinagre localhost:"$port"
	elif type vncviewer >/dev/null 2>&1; then
	    vncviewer localhost::"$port"
	elif type vnc4viewer >/dev/null 2>&1; then
	    vnc4viewer localhost::"$port"
	else
	    athrun outland vnc4viewer localhost::"$port"
	fi
	sleep 4
	echo moo
) >"$TMPFIFO"
