#!/bin/sh
# Name: startBhyveVm
# Purpose: A script to automatically start a Bhyve VM, handle reboots & shutdowns
# Author: S Bracewell 


# EXIT STATUS
#       Exit status indicates how the VM was terminated:
#
#       0       rebooted
#       1       powered off
#       2       halted
#       3       triple fault (amd64 only)
#       4       exited due to an error


# Param1: VM Name E.G. wardrobestores2guest
vmname=$1
# Param2: VM Path E.G. /tank/vms/vm4/
vmPath=$2

echo "First arg: $1"
echo "First arg: $2"
#sleep 120

i=0
#vmname=wardrobestores2guest


bhyveParams=

# Loop text file of Bhyve parameters and add them to a variable separated by a space
while IFS= read -r line; do
bhyveParams="$bhyveParams $line"
   # echo "Parameter: $line"
done < "$vmPath"params

echo $bhyveParams


#sleep 120

while [ "$i" -eq 0 ]
do
echo Bhyve Exit Code: "$i"
echo Starting "$vmname"

bhyve $bhyveParams $vmname

i=$?
done

echo Bhyve Exit Code: "$i"

if [ "$i" -ne 0 ]
then
bhyvectl --destroy --vm="$vmname"
echo "$vmname" destroyed
fi



