#!/usr/local/bin/cbsd
. ${subrdir}/nc.subr

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

# dialog_menu_main
#
# Display the dialog(1)-based application main menu.
#
dialog_menu_main()
{
	local _input _retval

	local btitle="$DIALOG_BACKTITLE"

	local title=" VHID list "
	hline=

	local prompt="${_desc}"
	local sqldelimer=" "

	local mark

	local menu_list=$( cbsdsqlro local "SELECT id,vhid,advskew,pass,peer,peer6,interface,state FROM carp" | while read id carp_vhid carp_advskew carp_pass carp_peer carp_peer6 interface carp_state; do
		eval mark=\$vhid_selected_${id}
		if [ "${mark}" = "1" ]; then
			mark="X"
		else
			mark=" "
		fi
		echo "'${id}'	'[${mark}] vhid=${carp_vhid} advskew=${carp_advskew}'	'interface=${interface};peer=${carp_peer};peer6=${carp_peer6};pass=${carp_pass};state=${carp_state}'"
	done ) || err 1 "${N1_COLOR}Error while create vhid map${N0_COLOR}"

	[ -z "${menu_list}" ] && menu_list="''	'no data'	''"

	local height width rows
	eval f_dialog_menu_with_help_size height width rows \
		\"\$title\"  \
		\"\$btitle\" \
		\"\$prompt\" \
		\"\$hline\"  \
		$menu_list

	height=$(( height + 1 ))

	# Obtain default-item from previously stored selection
	f_dialog_default_fetch defaultitem

	local menu_choice
	menu_choice=$( eval $DIALOG \
		--clear                                 \
		--title \"\$title\"                     \
		--backtitle \"\$btitle\"                \
		--hline \"\$hline\"                     \
		--item-help                             \
		--ok-label \"\$msg_ok\"                 \
		--cancel-label \"Remove\"               \
		--extra-button                          \
		--extra-label \"Add\"                   \
		--help-button				\
		--help-label \"Exit\"			\
		${USE_XDIALOG:+--help \"\"}             \
		--default-item \"\$defaultitem\"        \
		--menu \" \$prompt \"                   \
		$height $width $rows                    \
		$menu_list                              \
		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
	)

	local retval=$?
	f_dialog_data_sanitize menu_choice
	f_dialog_menutag_store "$menu_choice"

	# Only update default-item on success
	[ $retval -eq $DIALOG_OK ] && f_dialog_default_store "$menu_choice"
	return $retval
}


vhid_add()
{
	local _par VAL
	local btitle="$DIALOG_BACKTITLE"
	local prompt="Use menu to select and edit limit"
	local hline=

	local title=" Add VHID "
	local _mydesc

	local vhid advskew pass peer peer6 interface state

	while [ 1 ]; do

		# default
		[ -z "${carp_vhid}" ] && carp_vhid=1
		[ -z "${carp_advskew}" ] && carp_advskew=100
		[ -z "${carp_pass}" ] && carp_pass="navuhodonosor"
		[ -z "${carp_peer}" ] && carp_peer="224.0.0.18"
		[ -z "${carp_peer6}" ] && carp_peer6="ff02::12"
		[ -z "${interface}" ] && interface="auto"
		[ -z "${carp_state}" ] && carp_state="master"

		local menu_list=

		menu_list="
			'vhid'		'${carp_vhid}'		'vhid, must be integer, e.g.: 1'
			'advskew'	'${carp_advskew}'	'advertisement skew, 1-240, e.g: 100'
			'pass'		'${carp_pass}'		'password for vhid group'
			'peer'		'${carp_peer}'		'Unicast peer IPv4 address (or use 224.0.0.18 for Multicast'
			'peer6'		'${carp_peer6}'		'Unicast peer IPv6 address (or use ff02::12 for Multicast'
			'interface'	'${interface}'		'configured for interface, e.g: auto (uplink)'
			'state'		'${carp_state}'		'default state on boot: master or backup'
		"

		menu_list="${menu_list} 'COMMIT'	'Save changes and quit'	'Save!'"

		local height width rows
		eval f_dialog_menu_with_help_size height width rows \
			\"\$title\"  \
			\"\$btitle\" \
			\"\$prompt\" \
			\"\$hline\"  \
			$menu_list

		height=$(( height + 1 ))

		# Obtain default-item from previously stored selection
		f_dialog_default_fetch defaultitem

		mtag=$( eval $DIALOG \
			--clear                                 \
			--title \"\$title\"                     \
			--backtitle \"\$btitle\"                \
			--hline \"\$hline\"                     \
			--item-help                             \
			--ok-label \"\$msg_ok\"                 \
			--cancel-label \"Exit\"                 \
			${USE_XDIALOG:+--help \"\"}             \
			--default-item \"\$defaultitem\"        \
			--menu \" \$prompt \"                   \
			$height $width $rows                    \
			$menu_list                              \
			2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
		)

		local retval=$?
		f_dialog_data_sanitize mtag
		f_dialog_menutag_store "$mtag"

		# Only update default-item on success
		[ $retval -eq $DIALOG_OK ] && f_dialog_default_store "$mtag"

		case ${retval} in
			${DIALOG_OK})
				if [ "${mtag}" = "COMMIT" ]; then
					[ -z "${carp_vhid}" ] && f_dialog_msgbox "vhid must be filled" && continue
					[ -z "${carp_advskew}" ] && f_dialog_msgbox "advskew must be filled" && continue
					[ -z "${carp_pass}" ] && f_dialog_msgbox "vhid must be filled" && continue
					[ -z "${carp_peer}" ] && f_dialog_msgbox "peer must be filled" && continue
					[ -z "${carp_peer6}" ] && f_dialog_msgbox "peer6 must be filled" && continue
					[ -z "${interface}" ] && f_dialog_msgbox "interface must be filled" && continue
					[ -z "${carp_state}" ] && f_dialog_msgbox "state must be filled" && continue
					cbsdsqlrw local "INSERT INTO carp ( vhid,advskew,pass,peer,peer6,interface,state ) VALUES ( '${carp_vhid}','${carp_advskew}','${carp_pass}', '${carp_peer}', '${carp_peer6}', '${interface}', '${carp_state}' )"
					return ${retval}
				else
					get_construct_carp_${mtag}
					continue
				fi
				;;
			${DIALOG_CANCEL})
				return $retval
				;;
			*)
				return ${retval}
				;;
		esac
	done

}


vhid_remove()
{
	local _i
	local _vhids=

	for _i in $( /usr/bin/seq 1 128 ); do
		eval mark=\$vhid_selected_${_i}
		[ "${mark}" = "1" ] && _vhids="${_vhids} ${_i}"
	done

	for _i in ${_vhids}; do
		cbsdsqlrw local "DELETE FROM carp WHERE id='${_i}'"
	done
}


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

MYARG=""
MYOPTARG=""
MYDESC="Edit properties for vitual image of VM"
CBSDMODULE="bhyve"

. ${cbsdinit}

. ${subrdir}/settings-tui.subr
. ${dialog}
. ${subrdir}/carp.subr

#
# 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 " VHIDs "
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
	ret=$?

	case $ret in
		${DIALOG_OK})
			f_dialog_menutag_fetch mtag
			case "$mtag" in
				?" $msg_exit")
					break
					;;
				"-")
					continue
					;;
				*)
					vhid=${mtag%% *}
					# val=${mtag##* }
					eval mark=\$vhid_selected_${vhid}
					if [ "${mark}" = "1" ];then
						eval "vhid_selected_${vhid}=\"0\""
					else
						eval "vhid_selected_${vhid}=\"1\""
					fi
					;;
			esac
			;;
		${DIALOG_CANCEL})
			vhid_remove
			continue
			;;
		${DIALOG_EXTRA})
			vhid_add
			continue
			;;
		*)
			f_die
			;;
	esac
done

return $SUCCESS

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