#!/usr/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
	VMS="$2"
	shift 2
else
	VMS=$MARVIN_KVM_DOMAIN
fi

TIMEOUT=600
for VM in $(tr ',' '\n' <<< "$VMS")
do
	if `kvm-check-running "$VM"` ; 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

	RESTORE_PID=
	which kvm-boot-restore 2>/dev/null
	if [ $? -eq 0 ]; then
		screen -dmS kvm-boot-restore kvm-boot-restore $VM
	fi
	echo Starting $VM
	virsh start $VM
	STARTTIME=`date +%s`
	while ! `kvm-check-running "$VM"` ; do
		CURRENTTIME=`date +%s`
		RUNNING=$((CURRENTTIME-STARTTIME))
		if [ $RUNNING -gt $TIMEOUT ]; then
			echo "ERROR: 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 $(tr ',' '\n' <<< "$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
