#!/usr/bin/env cbsd
#v15.0.0
. ${subrdir}/nc.subr
. ${strings}
. ${tools}
CBSDMODULE="bhyve"
MYDESC="bhyve UEFI boot order TUI"
CIXARG="jname"
CIXOPTARG=""
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 Text user interface for managing bhyve UEFI boot order configuration.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}jname=${N0_COLOR}     - target virtual machine name.

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd bhyve-efivar-tui jname=vm1

${H3_COLOR}See also${N0_COLOR}:

  cbsd bhyve-efivar --help
  cbsd bconfig --help
  cbsd bget --help
  cbsd bset --help

"

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

dialog_menu_main()
{
	local title=" ${product} v${myversion} "
	local btitle="$DIALOG_BACKTITLE"
	local prompt="Use menu to select boot item and change order. Index is order (empty = disabled)"
	local defaultitem=
	local hline=
	local i=

	local menu_list=

	f_dialog_default_fetch defaultitem

	for i in ${name_list}; do
		eval _order=\$order_${i}
		eval _name=\$item_${i}
		if [ ${_order} -eq 1 ]; then
			_order="[*]"
		else
			_order="[ ]"
		fi
		menu_list="${menu_list} '${i}' '${_order} ${_name}' '${_name}'"
	done

	menu_list="${menu_list} '-' '' '' 'SAVE' '' 'Save boot order and exit'"

	cbsd_menubox_with_help
	retval=$?

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

	return $retval
}


### MAIN
. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && err 1 "${N1_COLOR}no such jail: ${N2_COLOR}${jname}${N0_COLOR}"
[ "${emulator}" != "bhyve" ] && err 1 "${N1_COLOR}Only for bhyve type VMs${N0_COLOR}"
shift #skip for jname

[ -z "${vm_vars_file}" ] && vm_vars_file="BHYVE_UEFI_VARS.fd"
VM_VARS="${jailsysdir}/${jname}/${vm_vars_file}"

[ ! -r "${VM_VARS}" ] && err 1 "${N1_COLOR}${CIX_APP}: no such UEFI VARS file: ${N2_COLOR}${VM_VARS}${N0_COLOR}"

name_list=
name_cnt=0

capture _efi_output ${ENV_CMD} NOCOLOR=1 bhyve-efivar jname="${jname}" header=0 human=0

while IFS='|' read _a _b _c; do
	[ -z "${_b}" ] && continue
	name_list="${name_list:+${name_list} }${_b}"
	name_cnt=$(( name_cnt + 1 ))
	if [ "${_a}" = "*" ]; then
		eval "order_${_b}=\"1\""
	else
		eval "order_${_b}=\"0\""
	fi
	eval "item_${_b}=\"${_c}\""
done <<< "${_efi_output}"

[ -z "${name_list}" ] && err 1 "${N1_COLOR}${CIX_APP}: no such VARS data: ${N2_COLOR}${VM_VARS}${N0_COLOR}"

while true; do
	dialog_menu_main || f_die

	f_dialog_menutag_fetch mtag

	case "${mtag}" in
		SAVE)
			new_boot=
			for i in ${name_list}; do
				eval _order=\$order_${i}
				if [ "${_order}" = "1" ]; then
					new_boot="${i#Boot}"
					break
				fi
			done

			if [ -n "${new_boot}" ]; then
				echo "${new_boot}"
				${miscdir}/efivar ${VM_VARS} -b 0000 > /dev/null 2>&1
				${miscdir}/efivar ${VM_VARS} -b ${new_boot}
			fi
			exit 0
			;;
		"-")
			continue
			;;
		*)
			for i in ${name_list}; do
				eval "order_${i}=\"0\""
			done
			export "order_${mtag}=1"
			;;
	esac
done

exit 0
