#!/usr/local/bin/cbsd
#v11.1.12
globalconf="${workdir}/cbsd.conf";

set -e
. ${globalconf}
set +e

. ${subr}
. ${strings}
. ${tools}

[ ! -f "${sharedir}/jail-arg" ] && err 1 "No such jail-arg skel"
. ${sharedir}/jail-arg
CBSDMODULE="xen"
MYDESC="Ncurses based setup for jail-arg"
MYARG="jname"
MYOPTARG="${JARG} outfile"

init $*

. ${settingstui}
. ${dialog}

commit()
{
	local _oldjname _newjname

	_oldjname="${jname}"

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

		if [ "${i}" = "jname" ]; then
			_oldjname="${OVAL}"
			_newjname="${VAL}"
			continue
		fi

		if [ "${i}" = "vm_ram" ]; then
			# In SQLite3 we store vm_ram in bytes, convert it
			# test for human
			if is_number ${VAL}; then
				if conv2bytes ${VAL}; then
					VAL="${convval}"
				fi
			else
				# Assume than user input in MB, so convert to bytes
				VAL=$(( convval * 1024 * 1024 ))
			fi
		fi

		[ "${VAL}" = "${OVAL}" ] && continue

		if [ "${i}" = "vm_ram" ]; then
			# In SQLite3 we store vm_ram in bytes, convert it
			VAL=$(( VAL / 1024 / 1024 ))
		fi

		xset mode=quiet jname=${_oldjname} ${i}="${VAL}"
	done

	[ "${_oldjname}" != "${_newjname}" -a -n "${_newjname}" ] && cbsd xrename old=${_oldjname} new=${_newjname}

	exit 0
}


store_defaults()
{
	local i VAL

	eval $( for i in "jname" ${JARG}; do
		[ "${i}" = "repo" ] && repo=1 && continue
		eval VAL=\$$i
		echo "OLDVAL_${i}=\"${VAL}\""
	done )
}


dialog_menu_main()
{
	title=" Config for ${jname} VM "
	hline=
	local defaultitem=

	local menu_list="
		'EXIT'  'EXIT'  'Exit jconstruct-tui'
	" # END-QUOTE

	local i _mytest skip
	local _checkbox="astart protected hidden"

	# don't show it in main menu:
	local _in_sub_menu="cd_vnc_wait xen_vnc_resolution xen_vnc_tcp_bind vnc_password"

	item_let="A"
	item_num=0

	 f_dialog_default_fetch defaultitem

	# checkbox mark
	for i in ${_checkbox}; do
		eval _mytest=\$$i
		if [ "${_mytest}" = "1" ]; then
			export ${i}_mark="X"
		else
			export ${i}_mark=" "
		fi
	done

	for i in ${JARG}; do
		skip=0

		# skip for _in_sub_menu list item:
		for y in ${_in_sub_menu}; do
				[ "${i}" = "${y}" ] && skip=1
		done

		[ ${skip} -eq 1 ] && continue

		for x in ${_checkbox}; do

			[ ${skip} -eq 1 ] && break

			if [ "${x}" = "${i}" ]; then
				eval _mytest=\$${x}_mark
				[ -z "${_mytest}" ] && _mytest=" "
				inc_menu_index item_let
				menu_list="${menu_list} '${item_let} ${x}'      '[${_mytest}]'  '${_mydesc}'"
				skip=1
			fi

		done

		[ ${skip} -eq 1 ] && continue

		inc_menu_index item_let

		eval VAL=\$$i

		if [ "${i}" = "vm_ram" ]; then
			# test for human
			if ! is_number ${VAL}; then
				if conv2human "${VAL}"; then
					VAL=${convval}
					vm_ram="${VAL}"
				fi
			fi
		fi

		if [ -z "${VAL}" ]; then
			menu_list="${menu_list} '${item_let} ${i}'	' '	'Descr?'"
		else
			menu_list="${menu_list} '${item_let} ${i}'	'${VAL}'	'Descr?'"
		fi
	done

	menu_list="${menu_list} '-'	'-' ''"
	menu_list="${menu_list} 'xendsk'	'Storage config >>'		'cbsd xendsk-tui'"
	menu_list="${menu_list} 'xennic'	'Network config >>'		'cbsd xennic-tui.'"
	#menu_list="${menu_list} 'xen_options'	'Xen options >>'		'Customize xen options: msi:${xen_force_msi_irq}'"

	if [ "${vm_efi}" != "none" ]; then
		menu_list="${menu_list} 'xen_vnc_options'	'VNC options >>'	'Customize VNC options: cd_wait:${cd_vnc_wait} resolution:${xen_vnc_resolution} bind:${xen_vnc_tcp_bind}'"
		inc_menu_index item_num
	fi

	menu_list="${menu_list} 'order'		'Boot order >>'			'cbsd border-tui'"
	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
. ${jrcconf}
[ $? -eq 1 ] && err 1 "${MAGENTA}No such jail: ${GREEN}${jname}${NORMAL}"
[ "${emulator}" != "xen" ] && err 1 "${MAGENTA}Only for xen type VMs${NORMAL}"

shift #skip for jname

# to rcconf?
A=$( cbsdsql ${jailsysdir}/${jname}/local.sqlite "SELECT vm_cpus,vm_ram,vm_os_type,vm_boot,vm_os_profile,vm_vnc_port,xen_vnc_tcp_bind,xen_vnc_resolution,cd_vnc_wait,protected,hidden,maintenance,ip4_addr,vnc_password FROM settings ORDER BY (created) DESC LIMIT 1;" )

if [ -n "${A}" ]; then
	OIFS="${IFS}"
	IFS="|"
	vm_cpus=
	vm_ram=
	vm_os_type=
	vm_boot=
	vm_os_profile=
	vm_vnc_port=
	xen_vnc_tcp_bind=
	xen_vnc_resolution=
	cd_vnc_wait=
	protected=
	hidden=
	maintenance=
	ip4_addr=
	vnc_password=
	sqllist "${A}" vm_cpus vm_ram vm_os_type vm_boot vm_os_profile vm_vnc_port xen_vnc_tcp_bind xen_vnc_resolution cd_vnc_wait protected hidden maintenance ip4_addr vnc_password
	IFS="${OIFS}"
else
	err 1 "${MAGENTA}Unable to fetch vm data from: ${GREEN}${jailsysdir}/${jname}/local.sqlite${NORMAL}"
fi

if [ ${jid} -ne 0 ]; then
	# Command for modifying on-the fly here:
	JARG="ip4_addr cpuset astart exec_consolelog protected hidden"
else
	JARG="$@"
fi

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

store_defaults

# fill promt variable used in dialog_menu_main about active jail status
# otherwise - append the argument that we can change also and jname.
if [ ${jid} -ne 0 ]; then
	prompt="VM is ONLINE. Only on-the-fly options printed."
else
	JARG="jname ${JARG}"
fi

while [ 1 ]; do
	dialog_menu_main || f_die

	index=${mtag%% *}
	mychoice=${mtag##* }

	case "${mychoice}" in
		"-")
			continue
			;;
		"xen_options")
			get_construct_xen_options
			;;
		"xen_vnc_options")
			get_construct_xen_vnc_options
			;;
		"xennic")
			xennic-tui jname=${jname}
			;;
		"xendsk")
			xendsk-tui jname=${jname}
			;;
		"order")
			border-tui jname="${jname}"
			;;
		"EXIT")
			f_die
			;;
		"COMMIT")
			commit
			;;
		astart|protected|hidden)
			invert_checkbox ${mychoice}
			continue
			;;
		interface)
			get_construct_interface -d 1 -s "tap bridge vboxnet"
			;;
		*)
			get_construct_${mychoice}
			;;
	esac
done
