#!/bin/bash

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

host=$1
num=$2
port=$(($num + 5900))
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:"$num"
	elif type vnc4viewer >/dev/null 2>&1; then
	    vnc4viewer localhost:"$num"
	else
	    athrun outland vnc4viewer localhost:"$num"
	fi
	echo moo
) >"$TMPFIFO"
