#!/usr/bin/env cbsd
#v12.0.4
CIXARG="mode"
CIXOPTARG="jname name type count cache"
MYDESC="Manage bhyve controller"
CBSDMODULE="bhyve"
EXTHELP="wf_bhyve"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 Manage storage controllers for a bhyve virtual machine.
 Attach or detach virtio-blk, ahci or nvme controllers, or list
 controllers currently configured for a domain.

 The controller name is the device identifier used in bhyve
 (e.g. virtio-blk0, ahci0). Type specifies the controller
 emulation type.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}mode=${N0_COLOR}     - action: attach, detach, list:
   attach - add a new controller to the domain;
   detach - remove a controller from the domain;
   list   - show controllers configured for the domain;
 ${N2_COLOR}jname=${N0_COLOR}    - target bhyve domain name;
 ${N2_COLOR}name=${N0_COLOR}     - controller name (e.g. virtio-blk0, ahci0);
 ${N2_COLOR}type=${N0_COLOR}     - controller type (e.g. virtio-blk, ahci, nvme);
 ${N2_COLOR}count=${N0_COLOR}    - number of disk slots on the controller;
 ${N2_COLOR}cache=${N0_COLOR}    - disk cache mode (e.g. writethrough, writeback).

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd bhyve-controller mode=attach jname=myvm name=virtio-blk0 type=virtio-blk count=4 cache=writethrough
 # cbsd bhyve-controller mode=detach jname=myvm name=virtio-blk0
 # cbsd bhyve-controller mode=list jname=myvm

${H3_COLOR}See also${N0_COLOR}:

  cbsd bconfig --help
  cbsd bhyve-dsk --help

"

. ${subrdir}/nc.subr
cixinit

. ${system}
. ${subrdir}/bhyve.subr
. ${subrdir}/virtual.subr
. ${CIX_DISTDIR}/share/bhyve/bhyve-controller.subr

ctr_attach()
{
	local _val
	for i in jname name type count cache; do
		_val=
		eval _val="\$$i"
		[ -z "${_val}" ] && err 1 "${N1_COLOR}bhyve-controller error: ${N2_COLOR}${i}= ${N1_COLOR}is mandatory${N0_COLOR}"
	done

	add_ctr -c "${count}" -n "${name}" -t "${type}" -z "${cache}"
}

ctr_detach()
{
	local _val
	for i in jname name; do
		_val=
		eval _val="\$$i"
		[ -z "${_val}" ] && err 1 "${N1_COLOR}bhyve-controller error: ${N2_COLOR}${i}= ${N1_COLOR}is mandatory${N0_COLOR}"
	done

	del_ctr -n "${name}"
}

case "${mode}" in
	attach)
		ctr_attach
		;;
	detach)
		ctr_detach
		;;
	list)
		bhyve-controller-list
		;;
	*)
		err 1 "${N1_COLOR}Unknown mode: ${N2_COLOR}${mode}${N0_COLOR}"
		;;
esac

exit 0
