#!/usr/local/bin/cbsd
#v11.0.10
CBSDMODULE="jail"
MYARG=""
MYOPTARG="jname"
MYDESC="Jail jstop jstart sequence"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

This script executes a stop-start sequence for a list of containers.

You may want to reload all active containers: to do this, just use the 
mask '*' as the 'jname'.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}jname=${N0_COLOR} - target jail. If jail='*' or jail='pri*' then start all jails or
          jails whose names begin with 'pri', e.g. 'prison1', 'prisonX'...

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd jrestart
 # cbsd jrestart jail1 jail2
 # cbsd jrestart jname='*'

${H3_COLOR}See also${N0_COLOR}:

 cbsd jstart --help
 cbsd jstop --help
 cbsd jorder --help

"

. ${subrdir}/nc.subr
. ${strings}
. ${tools}

if [ -z "$1" ]; then
	select_jail_by_list -s "List of online jail" -a "On" -r ${sqlreplica}
	jname="${jname}"
else
	jname="$*"
fi
. ${cbsdinit}

[ -z "${jname}" ] && return 0

emulator="jail"		# for jname_is_multiple
jname_is_multiple

if [ -z "${jail_list}" ]; then
	jail_list="${jname}"
fi

. ${subrdir}/time.subr
st_time=$( ${DATE_CMD} +%s )

if [ "${mod_cbsd_queue_enabled}" = "YES" -a -z "${MOD_CBSD_QUEUE_DISABLED}" ]; then
	readconf cbsd_queue.conf
	[ -z "${cbsd_queue_backend}" ] && MOD_CBSD_QUEUE_DISABLED="1"
fi

for jname in ${jail_list}; do
	. ${subrdir}/rcconf.subr

	if [ $? -eq 1 ]; then
		${ECHO} "${N1_COLOR}no such jail: ${N2_COLOR}${jname}${N0_COLOR}"
		continue
	fi

	# CBSD QUEUE
	if [ "${mod_cbsd_queue_enabled}" = "YES" -a -z "${MOD_CBSD_QUEUE_DISABLED}" ]; then
		[ -n "${cbsd_jail_queue_name}" ] && ${cbsd_queue_backend} cbsd_queue_name=${cbsd_jail_queue_name} id=${jname} cmd=jrestart status=1 workdir="${workdir}"
	fi

	cbsdlogger NOTICE ${CBSD_APP}: restarting ${jname}

	# restart atomic operation for high-level app, disable queue in jstop/jstart command
	jstop jname=${jname}
	jstart jname=${jname}

	myjid=$( cbsdsqlro local "SELECT jid FROM jails WHERE jname='${jname}'" 2>/dev/null )

	[ -z "${myjid}" ] && myjid=0

	if [ ${myjid} -eq 0 ]; then
		data_status=0
	else
		data_status=1
	fi

	if [ "${mod_cbsd_queue_enabled}" = "YES" -a -z "${MOD_CBSD_QUEUE_DISABLED}" ]; then
		[ -n "${cbsd_jail_queue_name}" ] && ${cbsd_queue_backend} cbsd_queue_name=${cbsd_jail_queue_name} id="${jname}" cmd=jrestart status=2 data_status=${data_status} workdir="${workdir}"
	fi

	end_time=$( ${DATE_CMD} +%s )
	diff_time=$(( end_time - st_time ))
	diff_time=$( displaytime ${diff_time} )
	${ECHO} "${N1_COLOR}${CBSD_APP} done ${N2_COLOR}in ${diff_time}${N0_COLOR}"
done

end_time=$( ${DATE_CMD} +%s )
diff_time=$(( end_time - st_time ))
diff_time=$( displaytime ${diff_time} )
${ECHO} "${N1_COLOR}${CBSD_APP} done ${N2_COLOR}in ${diff_time}${N0_COLOR}"

exit 0
