#!/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-start [-v] [-w] <vm1> <vm2>"
    echo "Usage: vm-start [-v] [-w] -p PREFIX [-a ARCH]"
    echo ""
    echo " -v        Do not launch virt-viewer on started VMs"
    echo " -w        Wait for VMs to be SSH-available before exiting"
}

start_machine() {
    machine="$1"
    if ! vm_exists $machine ; then
        echo "'$machine' does not exist" >&2
        return 1
    fi

    if vm_running $machine ; then
        echo "'$machine' is already running" >&2
        return 0
    fi

    virsh --connect ${vm_connect} start "$machine" 1>&2 || return 1
    if [ -n "$opt_viewer" ]; then
        sleep 0.5
        cd /tmp
        nohup virt-viewer --wait -c ${vm_connect} "$machine" >/dev/null &
        cd - >/dev/null
    fi

    echo "Sleeping 15 seconds to give '$machine' a chance to start" >&2
    sleep 15
    return 0
}

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

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

    for i in "$@" ; do
        machines="$machines $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
            machines="$machines $m"
        done
    done
fi

# Start each machine
started=""
for m in $machines ; do
    start_machine "$m" && started="$started $m"
done

# Wait for them to come up
if [ -n "$opt_wait" ]; then
    for m in $started ; do
        vm_wait "$m"
    done
fi

exit 0
