#!/bin/sh

# Bastille jail startup script
#
# PROVIDE: bastille
# REQUIRE: jail
# KEYWORD: shutdown

# Add the following to /etc/rc.conf[.local] to enable this service
#
# bastille_enable (bool):          Set to "NO" by default.
#                                  Set to "YES" to enable bastille.
# bastille_conf (bool):            Set to "/usr/local/etc/bastille/bastille.conf" by default.
#                                  Path to bastile.conf file.
# bastille_startup_delay (bool):   Set to "0" by default.
#                                  Set to a numerical value.
#                                  This is the delay between startup of each jail.
# bastille_parallel_limit (bool):  Set to "1" by default.
#                                  Set to a numerical value.
#                                  Number of processes to run in parallel when starting/stopping/restarting jails.
#

. /etc/rc.subr

name=bastille
rcvar=${name}_enable

: ${bastille_enable:="NO"}
: ${bastille_conf:="/usr/local/etc/bastille/bastille.conf"}
: ${bastille_startup_delay:=0}
: ${bastille_parallel_limit:=1}
: ${bastille_jail_list:=ALL}

command=/usr/local/bin/${name}
start_cmd="bastille_start"
stop_cmd="bastille_stop"
restart_cmd="bastille_restart"

list_jails() {
    local _jailsdir=$(. $bastille_conf; echo $bastille_jailsdir)
    local _jail_list=$(find ${_jailsdir}/* -mindepth 1 -maxdepth 1 -type f -name jail.conf | xargs -n1 dirname | xargs -n1 basename)
    for _jail in ${_jail_list}; do
        _priority="$(sysrc -f ${_jailsdir}/${_jail}/settings.conf -n priority)"
        echo "${_jail} ${_priority}"
    done
}

sort_jails() {
    local _order="${1}"
    if [ "${_order}" = "forward" ]; then
        bastille_jail_list="$(list_jails | sort -k2 -n | awk '{print $1}')"
    elif [ "${_order}" = "reverse" ]; then
        bastille_jail_list="$(list_jails | sort -k2 -nr | awk '{print $1}')"
    else
        echo "[ERROR]: Fatal error, could not get jail list."
    fi
}

bastille_start() {
    sort_jails "forward"
    echo "${bastille_jail_list}" | xargs -P ${bastille_parallel_limit} -I JAIL ${command} start --boot --delay ${bastille_startup_delay} JAIL
}

bastille_stop() {
    sort_jails "reverse"
    echo "${bastille_jail_list}" | xargs -P ${bastille_parallel_limit} -I JAIL ${command} stop JAIL
}

bastille_restart() {
    sort_jails "forward"
    echo "${bastille_jail_list}" | xargs -P ${bastille_parallel_limit} -I JAIL ${command} restart --boot --delay ${bastille_startup_delay} JAIL
}

load_rc_config ${name}
run_rc_command "$1"
