#!/usr/bin/env cbsd
#v10.0.5
CBSDMODULE="qemu"
CIXARG="jname"
CIXOPTARG="mode cmd"
MYDESC="Modify parameters for qemu domain (interactive/dialog)"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

You can edit available options for qemu 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 qconfig' without arguments
show a list of qemu to select. When qemu selected or specified as
an argument, 'qconfig' will launch a 'cbsd qsetup-tui' script.

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

${H3_COLOR}Options${N0_COLOR}:

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

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd qconfig

${H3_COLOR}See also${N0_COLOR}:

  cbsd qset --help

"
EXTHELP="wf_qconfig"

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

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

cixinit

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

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

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

cfgargs=
for i in ${@}; do
	[ "${i%%=*}" = "jname" ] && continue
	if [ -z "${cfgargs}" ]; then
		cfgargs="${i}"
	else
		cfgargs="${cfgargs} ${i}"
	fi
	[ -z "${cmd}" ] && cmd="${i}"
done

if [ -z "${cmd}" ]; then
	myargs="astart vm_cpus vm_ram vm_boot vm_vnc_port qemu_vnc_tcp_bind qemu_vnc_resolution \
	cd_vnc_wait protected hidden ip4_addr vnc_password on_poweroff on_reboot on_crash spice_default \
	vm_spice_port qemu_spice_tcp_bind qemu_spice_resolution qemu_spice_flags spice_password soundhw debug_engine \
	vm_iso_path machine machine_accel vga usb tablet xhci boot_delay kernel bios cpu nographic"

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

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

exit 0
