#!/usr/local/bin/cbsd
#v12.1.10
CBSDMODULE="jail"
MYARG="jname"
MYOPTARG="mode"
MYDESC="Modify parameters for jail (interactive/dialog)"
ADDHELP="\

${H3_COLOR}Description${N0_COLOR}:

You can edit available options for jail interactively, through the dialog(1) 
interface.  Some parameters can be applied while the container is running,
but most will require a container restart. 'cbsd jconfig' without arguments
show a list of containers to select. When jail selected or specified as
an argument, 'jconfig' will launch a 'cbsd jsetup-tui' script.

For non-interactive edit, please use 'cbsd jset' instead.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}mode=${N0_COLOR}      - set 'list' for list of jails external command;
 ${N2_COLOR}jname=${N0_COLOR}     - work with <jail>;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd jconfig

${H3_COLOR}See also${N0_COLOR}:

  cbsd jset --help

"

EXTHELP="wf_jconfig"

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

[ -z "${1}" ] && select_jail_by_list -s "List of local jails:" -r 1 -o 0
. ${cbsdinit}

shift  # todo: jname and cmd may have reverse order

. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && err 1 "${N1_COLOR}No such jail: ${N2_COLOR}${jname}${N0_COLOR}"
case "${emulator}" in
	jail|qemu*)
		;;
	*)
		err 1 "${N1_COLOR}${CBSD_APP}: for jail only (${emulator})${N0_COLOR}"
		;;
esac

CMDDIR="${jailsysdir}/${jname}/bin/"

if [ "${mode}" = "list" ]; then
	echo
	${ECHO} "${N1_COLOR}Additional command available: ${N2_COLOR}jconfig jname=${jname} <cmd>:${N0_COLOR}"
	[ -d "${CMDDIR}" ] && ${FIND_CMD} ${CMDDIR} -mindepth 1 -maxdepth 1 -type f -exec ${BASENAME_CMD} {} \;
	exit 0
fi

vimage=""
[ -z "${cmd}" ] && cmd=${1}
[ "${vnet}" ] && vimage="vnet"

shift
cfgargs="$@"

myargs=

if [ -z "${cmd}" ]; then
	myargs="allow_devfs allow_dying allow_fusefs allow_linprocfs allow_linsysfs allow_kmem allow_mount allow_nullfs allow_procfs allow_raw_sockets allow_reserved_ports \
	allow_tmpfs allow_zfs allow_mlock allow_nfsd applytpl arch astart basename baserw childrenmax cpuset devfs_ruleset enforce_statfs exec_consolelog exec_fib exec_start exec_stop \
	exec_timeout floatresolv hidden host_hostname interface ip4_addr jdomain mkhostsfile mount_devfs mount_fdescfs mount_procfs mount_linprocfs mount_linsysfs mount_kernel \
	mount_ports mount_src persist protected stop_timeout sysvmsg sysvsem sysvshm ver vnet ci_gw4 mnt_start mnt_stop boot_delay jnameserver"

	# allow_read_msgbuf for FreeBSD 12.0+
	[ ${freebsdhostversion} -gt 1200085 ] && myargs="${myargs} allow_read_msgbuf allow_vmm allow_unprivileged_proc_debug"

	sorted_myargs=$( for i in ${myargs}; do
		echo ${i}
	done | ${SORT_CMD} -n )

	jsetup-tui jname=${jname} ${sorted_myargs}

elif [ -f "${CMDDIR}${cmd}" ]; then
	. ${CMDDIR}${cmd}
	myconf ${cfgargs}
fi
