#!/usr/local/bin/cbsd
############################################################ INCLUDES

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

BSDCFG_LIBE="/usr/local/cbsd/share/libexec/bsdconfig" APP_DIR="cbsd"
BSDCFG_SHARE="/usr/local/cbsd/share/bsdconfig"
. ${BSDCFG_SHARE}/sysrc.subr
. ${BSDCFG_SHARE}/${APP_DIR}/include/messages.subr

############################################################ FUNCTIONS

# dialog_menu_main
#
# Display the dialog(1)-based application main menu.
#
dialog_menu_main()
{
	local title="$DIALOG_TITLE"
	local btitle="$DIALOG_BACKTITLE"
	local prompt=
	local menu_list= # Calculated below
	local defaultitem= # Calculated below
	local hline="$hline_arrows_tab_enter"

	[ -n "${cbsd_menu_defaultitem}" ] && defaultitem="${cbsd_menu_defaultitem}"

	local enable profiles
	enable=$( f_sysrc_get cbsdd_enable )
	jail_profiles=$( jls display=jname header=0 )
	bhyve_profiles=$( bls display=jname header=0 )

	local j
	j=$( set -- $jail_profiles; echo $# )
	local b
	b=$( set -- $bhyve_profiles; echo $# )

	local menu_list="
		'A ${msg_configure_jail_machines}'	'${j} ${msg_profiles}'
		'B ${msg_configure_bhyve_machines}'	'${b} ${msg_profiles}'
		'-'					'-'
		'1 ${msg_configure_initenv}'		''
		'2 ${msg_configure_nodes}'		''
		'3 ${msg_browse_repository}'		''
	" # END-QUOTE

	cbsd_menubox_simple
	retval=$?

	f_dialog_data_sanitize menu_choice
	f_dialog_menutag_store "${menu_choice}"
	f_dialog_default_store "${menu_choice}"

	return ${retval}
}

############################################################ MAIN
export NOCOLOR=1

#
# Process command-line arguments
#
while getopts h$GETOPTS_STDARGS flag; do
	case "${flag}" in
	h|\?) f_usage ${BSDCFG_LIBE}/${APP_DIR}/USAGE "PROGRAM_NAME" "${pgm}" ;;
	esac
done
shift $(( $OPTIND - 1 ))

#
# Initialize
#
f_dialog_title " ${msg_configure_cbsd} "
f_dialog_backtitle "${ipgm:+bsdconfig }${pgm}"
f_mustberoot_init

#
# Loop over the main menu until we've accomplished what we came here to do
#
while :; do
	dialog_menu_main || break
	f_dialog_menutag_fetch mtag

	export cbsd_menu_defaultitem="${mtag}"

	command=
	case "${mtag}" in
		?" ${msg_exit}") exit 0 ;;
		?" ${msg_configure_initenv}")
			/usr/local/bin/cbsd initenv-tui
			;;
		?" ${msg_configure_nodes}") command=node ;;
		?" ${msg_browse_repository}") command=repo ;;
		?" ${msg_configure_bhyve_machines}") command=bhyvecfg ;;
		?" ${msg_configure_jail_machines}") command=jailcfg ;;
		?" ${msg_configure_bhyve_machines}") command=bhyvecfg ;;
		?" ${msg_base_n_kernel}") command=basecfg ;;
	esac

	if [ -n "${command}" ]; then
		${BSDCFG_SHARE}/${APP_DIR}/${command} ${USE_XDIALOG:+-X}
	fi
done

exit ${SUCCESS}

################################################################################
# END
################################################################################
