#!/bin/sh

TIMEOUT=600

function usage() {
  echo "Stopping and starting virtual machine"
  echo "Usage:"
  echo "${0##*/} <xen vm config>"
	exit 1
}

if [ $# -eq 0 ]; then
	usage
fi

CONF="$1"

if [ `echo $TERM` != 'screen' ]; then
	echo "You are not in screen!"
	exit 1
fi

NAME=`grep ^name $1 | head -1 | sed 's/^name = "\(.*\)"/\1/'`

if [ -z "$NAME" ]; then
	echo "Virtual machine name not found. Invalid config file!"
	exit 1
fi

ID=`xl list | grep "^$NAME " | awk '{print $2}'`

if [ -z "$ID" ]; then
	echo "Virtual machine not started!"
	exit 1
fi

xl shutdown "$ID"
echo "Virtual machine $NAME shutdown are in progress"
NUM=0
while true; do
	if [ -z "$(xl list | awk '{print $2}' | grep ^$ID$)" ]; then
		break
	fi
	if [ $NUM -gt $TIMEOUT ]; then
		echo ""
		echo "Destroying virtual machine $NAME"
		xl destroy $ID
		break
	fi
	sleep 1
	((NUM++))
	printf .
done
echo ""

echo "Starting virtual machine $NAME"
xl create "$CONF"
exit 0

