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

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

f_include $BSDCFG_SHARE/sysrc.subr

BSDCFG_LIBE="/usr/local/libexec/bsdconfig" APP_DIR="cbsd"
f_include_lang $BSDCFG_LIBE/$APP_DIR/include/messages.subr

ipgm=$( f_index_menusel_keyword $BSDCFG_LIBE/$APP_DIR/INDEX "$pgm" )
[ $? -eq $SUCCESS -a "$ipgm" ] && pgm="$ipgm"

############################################################ 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"

	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

# Incorporate rc-file if it exists
[ -f "$HOME/.bsdconfigrc" ] && f_include "$HOME/.bsdconfigrc"

#
# 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

	command=
	case "$mtag" in
		?" $msg_exit") break ;;
		?" $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 [ "$command" ]; then
		$BSDCFG_LIBE/$APP_DIR/$command ${USE_XDIALOG:+-X}
	fi
done

return $SUCCESS

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