#!/usr/local/bin/cbsd
#v11.1.19
CBSDMODULE="bhyve"
MYARG="jname"
MYOPTARG="mode"
MYDESC="Pause and resume for bhyve domain (send STOP/CONT signal to bhyve vm process)"
ADDHELP="mode=[auto|on|off]\n\
  mode=auto (by default) triggering - e.g, if vm active then pause\n\
  mode=on - pause, stop\n\
  mode=off - unpause, continue\n"

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

. ${cbsdinit}

[ -z "${mode}" ] && mode="auto"

. ${subrdir}/rcconf.subr
if [ $? -eq 1 ]; then
	# try_remote
	log_err 1 "${N1_COLOR}No such vm: ${N2_COLOR}${jname}${N0_COLOR}"
fi
[ "${emulator}" != "bhyve" ] && log_err 1 "${N1_COLOR}Not in bhyve emulator: ${N2_COLOR}${emulator}{NORMAL}"

search_cmd="bhyve: ${jname}"
strlen_search_cmd=$( strlen "${search_cmd}" )

vm_pid=

eval $( /bin/ps axopid,state,ucomm,command -ww | while read pid state ucomm command; do
	[ "${ucomm}" != "bhyve" ] && continue
	cmd_pref=$( substr --pos=0 --len=${strlen_search_cmd} --str="${command}" )

	b_jname=$( echo "${command}" | ${AWK_CMD} '/bhyve: /{print $2}' )
	[ "${b_jname}" != "${jname}" ] && continue

	pid_count=$(( pid_count + 1 ))

	if $( echo "${state}" | ${GREP_CMD} -q "T" ); then
		pid_count=$(( pid_count - 1 ))
	fi

	if [ "${cmd_pref}" = "${search_cmd}" ]; then
		echo pid_count=\"${pid_count}\"
		echo vm_pid=\"${pid}\"
		break
	fi

	if echo "${command}" | ${GREP_CMD} -E -q -e " ${jname}"$ 2>/dev/null; then
		echo pid_count=\"${pid_count}\"
		echo vm_pid=\"${pid}\"
		break
	fi

done )

if [ -z "${vm_pid}" -o "${vm_pid}" = "0" ]; then
	cbsdlogger WARNING ${CBSD_APP}: unable to determine pid for: ${jname}
	log_err 1 "${N1_COLOR}Unable to determine pid for: ${N2_COLOR}${jname}${N0_COLOR}"
fi

if [ -z "${pid_count}" ]; then
	cbsdlogger WARNING ${CBSD_APP}: unable to determine pid_count for: ${jname}
	log_err 1 "${N1_COLOR}Unable to determine pid_count for: ${N2_COLOR}${jname}${N0_COLOR}"
fi

case "${mode}" in
	auto)
		if [ ${pid_count} -gt 0 ]; then
			cbsdlogger NOTICE ${CBSD_APP}: bhyve domain is active, triggering to sleep: ${jname}
			${ECHO} "${N1_COLOR}bhyve domain is active, triggering to sleep${N0_COLOR}"
			SIGNAL="STOP"
		else
			cbsdlogger NOTICE ${CBSD_APP}: bhyve domain is sleeping, triggering to continue: ${jname}
			${ECHO} "${N1_COLOR}bhyve domain is sleeping, triggering to continue${N0_COLOR}"
			SIGNAL="CONT"
		fi
		;;
	on)
		SIGNAL="STOP"
		;;
	off)
		SIGNAL="CONT"
		;;
esac

cbsdlogger NOTICE ${CBSD_APP}: send ${SIGNAL} signal to pid \(${jname}\): ${vm_pid}
kill -${SIGNAL} ${vm_pid}
