#!/bin/sh -e
#
# Copyright (C) 2007-2009 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#
# Simple starter script for when virt-manager won't do
#

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-stop [-f] <vm1> <vm2>"
    echo "Usage: vm-stop [-f] -p PREFIX [-a ARCH]"
    echo " -f    destroy rather than gracefully shutdown"
}

stop_machine() {
    command="$1"
    machine="$2"
    if ! vm_exists $machine ; then
        echo "'$i' does not exist"
        return
    fi

    if ! vm_running $machine ; then
        echo "'$machine' is not running"
        return
    fi

    virsh --connect ${vm_connect} $command "$machine" || return
    sent="yes"
}

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

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

    for i in "$@" ; do
        stop_machine $command "$i"
    done
else
    archs="$vm_archs"
    if [ ! -z "$arch" ]; then
        archs="$arch"
    fi

    for a in $archs ; do
        for m in `vm_get_machines_by_prefix "${prefix}" "$a"` ; do
            stop_machine $command "$m"
        done
    done
fi

if [ "$sent" = "yes" ] && [ "$command" = "shutdown" ]; then
    echo "Note: if virtual machine has a user that is logged into a desktop,"
    echo "the desktop user may need to confirm the shutdown operation."
fi

exit 0
