#!/bin/sh
#
# Copyright (C) 2007-2009 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#
# Simple viewer script to start virt-viewer for listed VMs
#

set -e

ustconf="$HOME/.uqt-vm-tools.conf"
if [ -s "$ustconf" ]; then
    . "$ustconf"
else
    echo "Could not find '$ustconf'"
    exit 1
fi

. $UQT_VM_TOOLS/libvm.sh
abort_if_root

help() {
    echo "Usage: vm-view <vm1> <vm2>"
    echo "Usage: vm-view -p PREFIX [-a ARCH]"
}

check_vm() {
    if ! vm_exists "$1" ; then
        echo "'$1' does not exist"
        return 1
    fi

    if ! vm_running "$1" ; then
        echo "'$1' is not running"
        return 1
    fi
    return 0
}

if [ -z "$1" ]; then
    help
    exit 1
fi

prefix=
while getopts "ha:p:" opt
do
    case "$opt" in
        a) arch="$OPTARG";;
        p) prefix="$OPTARG";;
        ?|h) help
           exit 1
           ;;
    esac
done
shift $(($OPTIND - 1))

cd /tmp
if [ -z "$prefix" ]; then
    for i in "$@" ; do
        if check_vm "$i" ; then
            nohup virt-viewer -c ${vm_connect} "$i" 2>/dev/null &
        fi
    done
else
    for a in $vm_archs ; do
        for m in `vm_get_machines_by_prefix "${prefix}" "$a"` ; do
            if check_vm "$m" ; then
                nohup virt-viewer -c ${vm_connect} "$m" 2>/dev/null &
            fi
        done
    done
fi

exit 0
