#!/bin/sh
set -eu
[ -r conf ] && . ./conf
: "${BHYVECTL:=/usr/sbin/bhyvectl}"

# bhyve@<name>@<mem>@<cpus>@<bridge>@<bootmethod>
myifs="${IFS}"
IFS="@"
i=0
for f in ${PWD}; do
	case ${i} in
	0) ;;
	1) name=${f} ;;
	2 | 3 | 4 | 5) ;;
	6) exit 1 ;;
	esac
	i=$((i + 1))
done
IFS="${myifs}"

[ -r "/dev/vmm/${name}" ] && ${BHYVECTL} --vm="${name}" --destroy
while read -r intf; do
	ifconfig "${intf}" destroy
done <supervise/network-interfaces

case "$1" in
0) ;; # rebooted
1 | 2 | 3 | 4)
	# Do not restart the VM when it
	# powered off | halted | triple faulted | exited due to an error
	# and require manual admin intervention to restart it
	sv down "${PWD}"
	;;
esac
