#!/usr/local/bin/cbsd
#v10.0.4
CBSDMODULE="bhyve"
MYARG="jname"
MYOPTARG="mode"
MYDESC="Modify parameters for bhyve domain (interactive/dialog)"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

You can edit available options for bhyve VM interactively, through the dialog(1)
interface.  Some parameters can be applied while the VM is running,
but most will require a VM restart. 'cbsd bconfig' without arguments
show a list of bhyve to select. When bhyve selected or specified as
an argument, 'bconfig' will launch a 'cbsd bsetup-tui' script.

For non-interactive edit, please use 'cbsd bset' instead.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}mode=${N0_COLOR}      - set 'list' for list of bhyves external command;
 ${N2_COLOR}jname=${N0_COLOR}     - work with <VM>;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd bconfig

${H3_COLOR}See also${N0_COLOR}:

  cbsd bset --help
  cbsd bhyve-dsk --help
  cbsd blpc --help
  cbsd bpcibus --help

"
EXTHELP="wf_bconfig"

. ${subrdir}/nc.subr
. ${tools}	# select_jail_by_list

[ -z "${1}" ] && select_jail_by_list -s "List of local VMs" -e bls -a "Off|On"

. ${cbsdinit}

shift  # todo: jname and cmd may have reverse order

. ${subrdir}/rcconf.subr
[ $? -eq 1 ] && log_err 1 "${N1_COLOR}no such jail: ${N2_COLOR}${jname}${N0_COLOR}"
[ "${emulator}" != "bhyve" ] && log_err 1 "${N1_COLOR}only for bhyve type VMs${N0_COLOR}"

CMDDIR="${jailsysdir}/${jname}/bin/"

if [ "${mode}" = "list" ]; then
	${ECHO} "${N1_COLOR}Configure command available: ${N2_COLOR}bconfig jname=${jname} <cmd>:${N0_COLOR}"
	[ -d "${CMDDIR}" ] && ${FIND_CMD} ${CMDDIR}  -mindepth 1 -maxdepth 1 -type f -exec ${BASENAME_CMD} {} \;
	exit 0
fi

[ -z "${cmd}" ] && cmd=${1}

shift
cfgargs="$@"

if [ -z "${cmd}" ]; then
	myargs="astart bhyve_flags bhyve_force_msi_irq bhyve_generate_acpi bhyve_ignore_msr_acc bhyve_mptable_gen bhyve_rts_keeps_utc \
	bhyve_vnc_resolution bhyve_vnc_tcp_bind bhyve_vnc_vgaconf bhyve_wire_memory bhyve_x2apic_mode cd_boot_firmware cd_vnc_wait cpuset \
	debug_engine hidden ip4_addr on_crash on_poweroff on_reboot protected vm_boot vm_cpu_topology vm_cpus vm_efi vm_hostbridge \
	vm_iso_path vm_ram vm_vnc_port vnc_password xhci tablet fbuf double_acpi virtio_rnd uuid hdd_boot_firmware bhyverun_wrapper \
	boot_delay bhyve_cmd bhyve_vnc_kbdlayout tpm"

	# jailed for FreeBSD 12.0+
	[ ${freebsdhostversion} -gt 1200086 ] && myargs="${myargs} jailed"
	#myargs="${myargs} chrooted"

	# hda for FreeBSD 13.0+
	[ ${freebsdhostversion} -gt 1300034 ] && myargs="${myargs} soundhw"

	sorted_myargs=$( for i in ${myargs}; do
		echo ${i}
	done | ${SORT_CMD} -n )

	bsetup-tui jname=${jname} ${myargs}
elif [ -f "${CMDDIR}${cmd}" ]; then
	. ${CMDDIR}${cmd}
	myconf ${cfgargs}
fi

exit 0
