#!/bin/bash

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

# Simply resume if the VM was saved
VBoxManage showvminfo "$1" |grep "^State:\s*saved" >/dev/null && {
	echo "Resuming $1 ..."
        VBoxManage startvm "$1" >/dev/null || {
                echo Erreur au demarrage de $1
                exit 1
        }
	sleep 5
	exit 0
}

# Now, start the VM if needed
VBoxManage showvminfo "$1" |grep "^State:\s*running" >/dev/null || {
	# Start the VM
	echo "Starting $1 ..."
	VBoxManage startvm "$1" >/dev/null || {
		echo Erreur au demarrage de $1
		exit 1
	}
	# Wait for status "running" to appear
        while ! ( VBoxManage showvminfo "$1" |grep "^State:\s*running" >/dev/null );
        do sleep 1;
        done;

	# Now wait for the guest extension to load, but not more that 5 minutes
	VBoxManage guestproperty wait "$1" /VirtualBox/GuestInfo/OS/NoLoggedInUsers --timeout 300000 --fail-on-timeout >/dev/null || {
		echo Impossible de detecter le demarrage de la VM $1
		exit 1
	}

	# Leave a few additional seconds for login prompt to appear
	sleep 10
}

# Login in the VM
./vm_login.sh "$1"

# Now, check the network is started // Finally, we force it in any case...
#VBoxManage guestproperty get "$1" /VirtualBox/GuestInfo/Net/0/V4/IP | grep "^Value:\s*192.168" >/dev/null || {
	# Issue a dhclient eth0 in this case
	VBoxManage controlvm "$1" keyboardputscancode 20 a0 23 a3 2e ae 26 a6 17 97 12 92 31 b1 14 94 39 b9 12 92 14 94 23 a3 0b 8b 1c 9c >/dev/null
	sleep 5
# }

# Done
echo "$1 should be running fine now"

