#!/usr/bin/env cbsd
#v11.0.16
CBSDMODULE="bhyve"
CIXARG=""
CIXOPTARG="jname mode editor"
MYDESC="Show or modify jail description"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 Display or edit the description file of a bhyve virtual machine.
 In normal mode (no mode= argument), prints the description to stdout.
 With mode=update, opens the description file in an editor for editing.
 When jname= is omitted, lists descriptions for all bhyve domains.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}jname=${N0_COLOR}   - target bhyve domain name. If omitted, show all domains;
 ${N2_COLOR}mode=${N0_COLOR}    - set to 'update' to edit the description file;
 ${N2_COLOR}editor=${N0_COLOR}  - editor to use for editing. Default: 'nvi';

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd bdescr jname=myvm
 # cbsd bdescr mode=update jname=myvm
 # cbsd bdescr mode=update jname=myvm editor=mcedit
 # cbsd bdescr

${H3_COLOR}See also${N0_COLOR}:

  cbsd bconfig --help

"
EXTHELP="wf_jdescr"

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

cixinit

showdescr()
{
	SYSDIR="${jailsysdir}/${jname}"
	PDESCR="${SYSDIR}/descr"

	if [ "${mode}" = "update" ]; then
		[ ! -d "${SYSDIR}" ] && ${MKDIR_CMD} -m 0775 -p ${SYSDIR}
		${TOUCH_CMD} ${PDESCR} && ${CHOWN_CMD} ${cbsduser}:${cbsduser} ${PDESCR}
		cbsdlogger NOTICE ${CIX_APP}: edit domain description for: ${jname}
		${editor} "${PDESCR}"
	else
		[ -f "${PDESCR}" ] && ${CAT_CMD} ${PDESCR}
	fi
}

showall()
{
	local jname _jnames

	capture _jnames cbsdsqlro local "SELECT jname FROM jails WHERE emulator='bhyve' ORDER BY jname ASC"
	for jname in ${_jnames}; do
		[ -z "${jname}" ] && continue
		${ECHO} "${BOLD}${jname} {${N0_COLOR}"
		showdescr
		${ECHO} "${BOLD}}${N0_COLOR}"
	done
}

[ -z "${editor}" ] && editor="nvi"

if [ -z "${jname}" ]; then
	showall
else
	. ${subrdir}/rcconf.subr
	[ $? -eq 1 ] && err 1 "${N1_COLOR}No such jail: ${N2_COLOR}${jname}${N0_COLOR}"
	showdescr
fi

exit 0
