#!/bin/bash 

# Check params
if [ -z "$1" ]; then echo "Donnez le nom de la VM en parametre"; exit 1; fi

VM=$1
shift

# First, check the VM is running
VBoxManage showvminfo "$VM" |grep "^State:\s*running" >/dev/null || {
	echo $VM already stopped.
	exit 0
}

echo "Shutting down $VM..."

if [ "$1" = "nochgcns" ];
then
	shift
else
	# Change console to the 5th (alt-F5)
	VBoxManage controlvm "$VM" keyboardputscancode 38 3f bf b8 >/dev/null
	
	sleep 2

	# Login in the VM
	./vm_login.sh "$VM" force
fi

# Issue a "shutdown -h now" order
VBoxManage controlvm "$VM" keyboardputscancode 1f 9f 23 a3 16 96 14 94 20 a0 18 98 11 91 31 b1 39 b9 0c 8c 23 a3 39 b9 31 b1 18 98 11 91 1c 9c >/dev/null

# Wait for shutdown complete if told to
if [ "$1" = "waitterm" ]; then
	while ( VBoxManage showvminfo "$VM" |grep "^State:\s*running" >/dev/null );
	do sleep 1;
	done
	echo $VM was shutdown
fi
# Done

