#!/bin/sh

# Add the following lines to /etc/rc.conf to enable chyves:
#
# chyves_enable="YES"
# chyves_flags="pool=zroot kmod=1 net=em0"
#
# PROVIDE: chyves
# REQUIRE: LOGIN sshd
#

. /etc/rc.subr

name="chyves"
rcvar=chyves_enable

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

start_cmd="__chyves_start"
stop_cmd="__chyves_stop"

__chyves_start()
{
	echo "Starting chyves guests..."
	sleep 8 # Sleeping for network to come up.
	local _previous_stdout_level="$( /usr/local/sbin/chyves list global | grep stdout_level | awk '{ print $2 }' )"
	/usr/local/sbin/chyves global set stdout_level=0
	local _guestlist="$( grep -H -E '^rcboot=' /chyves/*/guests/*/.config/.cfg | awk 'BEGIN { FS = "=" } ; $2 > "0" { print $1" "$2 }' | sort -Vrk2 | cut -d'/' -f5 | tr '\n' ',' | sed 's/,$//g' )"
	echo "Starting chyves guests ($_guestlist)..."
	/usr/local/sbin/chyves $_guestlist start
	echo "Guests starting, resuming host boot."
	sleep 3
	/usr/local/sbin/chyves global set stdout_level="$_previous_stdout_level"
}

__chyves_stop()
{
	echo "Stopping all chyves guests..."
	/usr/local/sbin/chyves all stop
}

run_rc_command "$1"
