#!/usr/local/bin/cbsd
#v10.0.6
globalconf="${CIX_DISTDIR}/cbsd.conf";
CIXARG=""
CIXOPTARG="emulator jname nodename"
MYDESC="Return node for environment"
ADDHELP="
${H3_COLOR}Description${N0_COLOR}:

 When you work with several nodes in a cluster (via a 'cbsd node mode=add'), 
CBSD periodically exchange information about their state and inventory. 
This command will return the node for the environment, whether it is local or not.

${H3_COLOR}Options${N0_COLOR}:

 ${N2_COLOR}emulator=${N0_COLOR} - <emulator>, search for 'emulator' engine, default: 'jail',
                       full list: 'bhyve', 'jail', 'qemu', xen', 'virtualbox';
 ${N2_COLOR}jname=${N0_COLOR}    - <emulator>, search for 'jname' environment;

${H3_COLOR}Examples${N0_COLOR}:

 # cbsd jwhereis jail2 jail6

"

. ${subrdir}/nc.subr
nodename=
cixinit

[ -z "$1" ] && err 1 "jwhereis: give me args"
: "${emulator:=jail}"
[ -z "${nodename}" ] && cbsdsqlro_vars nodes "SELECT nodename FROM nodelist"

for _jname in ${jname} ${CIX_OTHER_ARGS}; do
	for i in local ${nodename}; do
		cbsdsqlro_vars "${i}" "SELECT jname FROM jails WHERE jname='${_jname}' AND emulator='${emulator}' LIMIT 1" exist
		if [ -n "${exist}" ]; then
			[ "${i}" = "local" ] && i="${nodename}"
			echo "${i}"
		fi
	done
done

exit 0
