#!/usr/local/bin/cbsd
#v10.0.6
globalconf="${distdir}/cbsd.conf";
MYARG=""
MYOPTARG="emulator jname"
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
. ${cbsdinit}

[ -z "$1" ] && err 1 "jwhereis: give me args"
[ -z "${emulator}" ] && emulator="jail"
[ -z "${node}" ] && node=$( cbsdsqlro nodes SELECT nodename FROM nodelist 2>/dev/null )

for jname in $*; do

	prefix6=$( substr --pos=0 --len=6 --str=${jname} )
	prefix9=$( substr --pos=0 --len=9 --str=${jname} )
	[ "${prefix9}" = "emulator=" ] && continue
	[ "${prefix6}" = "jname=" ] && continue

	for i in local ${node}; do
		exist=
		exist=$( cbsdsqlro ${i} "SELECT jname FROM jails WHERE jname=\"${jname}\" AND emulator=\"${emulator}\" LIMIT 1" 2>/dev/null )
		if [ -n "${exist}" ]; then
			[ "${i}" = "local" ] && i="${nodename}"
			echo ${i}
		fi
	done
done

exit 0
