#!/usr/local/bin/cbsd
#v10.0.4
CBSDMODULE="qemu"
MYARG="jname"
MYOPTARG="mode"
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}	# select_jail_by_list

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

. ${cbsdinit}

# todo: jname and cmd may have reverse order
[ $# -gt 0 ] && shift

. ${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

[ -z "${cmd}" ] && cmd=${1}
[ $# -gt 0 ] && shift

cfgargs="$@"

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"
	#myargs="${myargs} chrooted"

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

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

exit 0
