#!/bin/sh

# Add the following lines to /etc/rc.conf to enable iohyve:
#
# iohyve_enable="YES"
#
# PROVIDE: iohyve
# REQUIRE: LOGIN sshd
#

. /etc/rc.subr

name="iohyve"
rcvar=iohyve_enable

# read configuration and set defaults
load_rc_config "$name"
: ${iohyve_enable="NO"}
: ${iohyve_flags=""}

start_cmd="iohyve_start"
stop_cmd="iohyve_stop"

iohyve_start()
{
	echo "Starting iohyve guests..."
	/usr/local/sbin/iohyve setup ${iohyve_flags}
	local guests="$(zfs get -H -s local,received -o name,value -t filesystem iohyve:name | tr '\t' ',')"
	for guest in $guests ; do
		local dataset="$(echo $guest | cut -f1 -d,)"
		local name="$(echo $guest | cut -f2 -d,)"

		local bootprop="$(zfs get -H -o value iohyve:boot $dataset)"
		if [ $bootprop = "1" ]; then
			# Check dataset depth, used to ignore replication targets with boot=1 set
			# normally dataset = "$pool/iohyve/$name"
			depth="$(printf "$dataset" | grep -o "/" | wc -l)"
			
			if [ "$depth" -eq 2 ]; then
				printf "Starting $dataset\n"
				/usr/local/sbin/iohyve start $name
			else
				printf "Skipping $dataset: Guest has non-standard path\n"
			fi
		fi
	done
}

iohyve_stop()
{
	echo "Stopping all iohyve guests..."
	/usr/local/sbin/iohyve scram
}

run_rc_command "$1"
