#!/bin/bash
#
# This script starts one or more existing VMs.
#
# The list of the VM names is passed as first (and only)
# parameter, i.e., `--vm foo,bar`. If no parameter is passed,
# it it assumed that there will be one VM, whose name is either
# defined in $MARVIN_KVM_DOMAIN, or it's 'marvin-mmtests'

if [ "$MARVIN_KVM_DOMAIN" = "" ]; then
	export MARVIN_KVM_DOMAIN="marvin-mmtests"
fi

if [ "$1" = "--vm" ]; then
	shift
	VMS="$1"
	shift
else
	VMS=$MARVIN_KVM_DOMAIN
fi

TIMEOUT=600
IFS=,
for VM in $VMS; do
	if [ "`virsh list | grep " $VM " | awk '{print $3}'`" = "running" ]; then
		echo $VM already running according to virsh
		GUEST_IP=`kvm-ip-address --vm $VM 0`
		if [ $? -eq 0 ]; then
			wait_ssh_available $GUEST_IP
			continue
		fi
	fi

	echo Starting $VM
	virsh start $VM
	STARTTIME=`date +%s`
	while [ "`virsh list | grep " $VM " | awk '{print $3}'`" != "running" ]; do
		CURRENTTIME=`date +%s`
		RUNNING=$((CURRENTTIME-STARTTIME))
		if [ $RUNNING -gt $TIMEOUT ]; then
			echo Timeout exceeded for $VM to become \'running\'
			exit -1
		else
			sleep 1
		fi
	done
	echo Console available via \"virsh console $VM\"
done

for VM in $VMS; do
	echo Waiting on $VM IP
	GUEST_IP=`kvm-ip-address --vm $VM 600`
	if [ $? -eq 0 ]; then
		wait_ssh_available $GUEST_IP
		if [ $? -ne 1 ]; then
			echo ERROR: Unable to start $VM
			exit -1
		fi
	fi
done
exit 0
