#!/bin/bash

vmName="$1"
gui=$2
bootdevice=$3

export LC_ALL=C

#Give the OS in the VM 10 seconds to shut down
sleep 10

# Get the VM's name in camelCase
export vmName="$(VBoxManage list vms | grep -i "\"$vmName\"" | cut -d '"' -f2)"

#Power off the VM and wait until it is really powered off
while [ $(VBoxManage showvminfo "$vmName" | grep "State:" | grep 'powered off' -c) -eq 0 ]
do
	VBoxManage controlvm "$vmName" poweroff
	sleep 1
done

#Change the first boot device and wait until it is really set to the desired boot device
while [ $(VBoxManage showvminfo "$vmName" | grep 'Boot Device (1)' | cut -d':' -f2 | grep -i -c $bootdevice) -eq 0 ]
do
	if [ `VBoxManage --version | cut -d'.' -f1` -eq 2 ]
	then
		VBoxManage modifyvm $vmName -boot1 $bootdevice;
	else
		VBoxManage modifyvm $vmName --boot1 $bootdevice;
	fi
	sleep 1
done

#Start the Vm again
if [ $gui -eq 0 ]
then
	nr=$(cat "/tmp/$vmName.vnc" | cut -d':' -f2 | head -1)
	export DISPLAY=":$nr"
	VBoxManage startvm "$vmName" --type gui
else
	VBoxHeadless -s "$vmName"
fi