#!/bin/sh

# PROVIDE: pot
# REQUIRE: NETWORKING LOGIN FILESYSTEM
# BEFORE: securelevel
# KEYWORD: shutdown nojail

. /etc/rc.subr

PATH=$PATH:%%PREFIX%%/bin
name="pot"
desc="Pot containers"
procname="pot"
rcvar=pot_enable
start_cmd="pot_start"
stop_cmd="pot_stop"
restart_cmd="pot_restart"
status_cmd="pot_status"

load_rc_config $name
: ${pot_enable:=NO}

pot_start()
{
	local _pname _dyn_pot_list _start
	_dyn_pot_list=$(%%PREFIX%%/bin/pot ls -q)
	for _pname in $_dyn_pot_list ; do
		if [ "$( %%PREFIX%%/bin/pot get-attr -p "$_pname" -A start-at-boot -q )" = "YES" ]; then
			%%PREFIX%%/bin/pot start "$_pname"
		fi
	done
}

pot_stop()
{
	local _pname _dyn_pot_list _start
	_dyn_pot_list=$(%%PREFIX%%/bin/pot ls -q)
	for _pname in $_dyn_pot_list ; do
		if [ "$( %%PREFIX%%/bin/pot get-attr -p "$_pname" -A start-at-boot -q )" = "YES" ]; then
			%%PREFIX%%/bin/pot stop "$_pname"
		fi
	done
}

pot_early_start()
{
	local _pname _dyn_pot_list _start
	_dyn_pot_list=$(%%PREFIX%%/bin/pot ls -q)
	for _pname in $_dyn_pot_list ; do
		if [ "$( %%PREFIX%%/bin/pot get-attr -p "$_pname" -A early-start-at-boot -q )" = "YES" ]; then
			%%PREFIX%%/bin/pot start "$_pname"
		fi
	done
}

pot_early_stop()
{
	local _pname _dyn_pot_list _start
	_dyn_pot_list=$(%%PREFIX%%/bin/pot ls -q)
	for _pname in $_dyn_pot_list ; do
		if [ "$( %%PREFIX%%/bin/pot get-attr -p "$_pname" -A early-start-at-boot -q )" = "YES" ]; then
			%%PREFIX%%/bin/pot stop "$_pname"
		fi
	done
}

pot_restart()
{
	pot_stop
	pot_early_stop
	sleep 5
	pot_early_start
	pot_start
}

pot_status()
{
	local _pname _dyn_pot_list
	_dyn_pot_list=$(%%PREFIX%%/bin/pot ls -q)
	for _pname in $_dyn_pot_list ; do
		if [ "$( %%PREFIX%%/bin/pot get-attr -p "$_pname" -A early-start-at-boot -q )" = "YES" ] ||
		   [ "$( %%PREFIX%%/bin/pot get-attr -p "$_pname" -A start-at-boot -q )" = "YES" ]; then
			if %%PREFIX%%/bin/pot info -qrp "$_pname" ; then
				echo "pot $_pname is up and running"
			else
				echo "pot $_pname is not running"
			fi
		fi
	done
}

run_rc_command "$1"
