#!/usr/local/bin/cbsd
#v11.1.12
MYARG=""
MYOPTARG="fw_new natip_new"
MYDESC="Configuring NAT in text-user dialog"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

TUI interface for 'cbsd natcfg' script.

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd natcfg-tui
 # cbsd natcfg-tui fw_new=pf natip_new=192.168.0.1

${H3_COLOR}See also${N0_COLOR}:

 cbsd natcfg --help
 cbsd naton --help
 cbsd natoff --help
 cbsd expose --help
 cbsd initenv-tui --help

"

. ${subrdir}/nc.subr

ofw_new=
onatip_new=
fw_new=
natip_new=
. ${cbsdinit}

[ -n "${fw_new}" ] && ofw_new="${fw_new}"
[ -n "${natip_new}" ] && onatip_new="${natip_new}"

. ${system}
. ${initenv}

# form-based version
#forms module=natcfg jname=CBSDSYS

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

commit()
{
	local modified=0

	for i in nat_enable natip; do
		eval VAL=\$$i
		eval OVAL=\$OLDVAL_${i}

		[ "${VAL}" = "${OVAL}" ] && continue
		${ECHO} "${i}: ${N1_COLOR}changed${N0_COLOR}"
		cbsdsqlrw local "UPDATE local SET ${i}='${VAL}'"
		modified=1
	done

	if [ ${modified} -eq 1 ]; then
		env sqlcolnames="1" ${miscdir}/sqlcli ${dbdir}/local.sqlite "SELECT * FROM local" > ${inventory}
		case "${nat_enable}" in
			disable|0)
				cbsd natoff
				;;
			*)
				natoff
				natcfg fw_new="${nat_enable}" natip_new="${natip}"
				naton
				;;
		esac
	fi

	exit 0
}

store_defaults()
{
	local i VAL

	eval $( for i in nat_enable natip; do
		eval VAL=\$$i
		echo "OLDVAL_${i}=\"${VAL}\""
	done )
}

dialog_menu_main()
{
	local title=" natcfg "
	hline=
	local defaultitem=

	f_dialog_default_fetch defaultitem

	local menu_list=

	menu_list="${menu_list} 'nat_enable'	'${nat_enable}'		'Which NAT framework do you want to use: pf, ipfw, ipfilter or disabled'"
	menu_list="${menu_list} 'natip'		'${natip}'		'Set IP address or NIC as the aliasing NAT address or interface'"
	menu_list="${menu_list} '-'     '-' ''"
        menu_list="${menu_list} 'COMMIT'        'Save changes and quit' 'Save!'"
	cbsd_menubox
	retval=$?

	f_dialog_data_sanitize menu_choice
	f_dialog_menutag_store "$menu_choice"
	f_dialog_default_store "$menu_choice"

	return $retval
}


### MAIN
f_dialog_title "$msg_system_console_configuration"
f_dialog_backtitle "${ipgm:+bsdconfig }$pgm"
f_mustberoot_init

[ -n "${ofw_new}" ] && nat_enable="${ofw_new}"
[ -n "${onatip_new}" ] && natip="${onatip_new}"

store_defaults

[ "${nat_enable}" = "0" ] && nat_enable="disable"

while [ 1 ]; do
	dialog_menu_main || f_die

	index=${mtag%% *}
	mychoice=${mtag##* }
                
	case "${mychoice}" in
		"-")
			continue
			;;
		nat_enable)
			get_initenv_nat_enable
			;;
		natip)
			get_initenv_natip
			;;
		"COMMIT")
			commit
			;;
	esac
done

exit 0
