#!/usr/bin/bash
#
# This script stops 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

for VM in $(tr ',' '\n' <<< "$VMS")
do
	# Does virsh think it's running?
	if ! `kvm-check-running "$VM"` ; then
		echo "Not stopping $VM as it is not running..."
		continue
	fi
	echo "Shutting down $VM"
	virsh shutdown $VM
done

for VM in $(tr ',' '\n' <<< "$VMS")
do
	# Even if it was running before, it may be shutdown by now...
	if ! `kvm-check-running "$VM"` ; then
		continue
	fi

	echo -n "Waiting on $VM shutdown to complete"
	DURATION=0
	while `kvm-check-running "$VM"`
	do
		echo -n .
		sleep 5

		DURATION=$((DURATION+5))
		if [ $DURATION -gt 30 ]; then
			echo -en "\nWARNING: Normal $VM shutdown exceeded, destroying"
			virsh destroy $VM
			DURATION=0
		fi
	done
	echo -en "\n"
done
