#!/bin/bash

# Shuts down a VirtualBox VM and does not return until the VM is not running

# Usage
#   * $1 the name of the VirtualBox VM to shut down
#   * Intended for use from a systemd service, named by ExecStop

function msg {
    echo "$0: $1" >&2
    logger -t "${0#*/}" "$1"
    exit 1
}

# Parse arguments
(($#==0)) && msg 'mandatory first argument missing'
(($#>1)) && msg "too many arguments: $*"
vmname=$1
logger -t "${0#*/}" "vmname: $vmname"

# Initiate shutdown
cmd=(VBoxManage controlvm "$vmname" acpipowerbutton)
logger -t "${0#*/}" "Running ${cmd[*]}"
out=$("${cmd[@]}" 2>&1)
[[ $out != '' ]] && msg "Unexpexted output from ${cmd[*]}:"$'\n'"$out"

# Wait until not running
cmd=(VBoxManage list runningvms)
while true
do
    sleep 0.2
    logger -t "${0#*/}" "Running ${cmd[*]}"
    out=$("${cmd[@]}" 2>&1)
    (($?!=0)) && msg "Unexpexted output from ${cmd[*]}:"$'\n'"$out"
    echo "$out" | grep "$vmname" >/dev/null
    (($?!=0)) && exit 0
    logger -t "${0#*/}" "$vmname still in runningvms list"
done
