#!/bin/bash

function usage () {
    echo "Usage:"
    echo "   `basename $0` -h <xenserver host> -g <guest vm name-label>"
    echo "   `basename $0` -h <xenserver host> -u <guest vm uuid>"
    exit 1
}

while getopts "h:g:u:" option
do
    case $option in
        h ) xs=${OPTARG} ;;
        g ) vm=${OPTARG} ;;
        u ) uu=${OPTARG} ;;
        * ) usage
    esac
done

if [ -z ${xs} ]; then
    usage
fi

if [ -z ${uu} ] && [ -z ${vm} ]; then
    usage
fi

if [ ! -z ${uu} ]; then
    domid=`ssh root@${xs} xe vm-list uuid=${uu} params=dom-id --minimal`
elif [ ! -z ${vm} ]; then
    domid=`ssh root@${xs} xe vm-list name-label=${vm} params=dom-id --minimal`
fi

if [ -z ${domid} ]; then
    echo "Could not find guest ${vm}${uu} on host ${xs}."
    exit 1
fi

port=`ssh root@${xs} xenstore-read /local/domain/${domid}/serial/0/vnc-port`

echo "Connecting to vnc port ${port} on host ${xs}..."

vncviewer -via root@${xs} localhost::${port}
