#!/usr/local/bin/cbsd
#v12.1.11
MYARG=""
MYOPTARG="cbsdfile cur_env cwd jname"
MYDESC="State of the cluster CBSDfile is managing, via CBSD API"
CBSDMODULE="sys"
ADDHELP="\
 (experimental)\n\
 cbsdfile - alternative path to CBSDfile, could be relative to the\n\
   working directory like: tmp/CBSDfile\n\
"
EXTHELP="wf_cbsdfile"

. ${subrdir}/nc.subr
. ${strings}
cwd=
jname=
CLOUD_URL=
CLOUD_KEY=
. ${cbsdinit}

[ -z "${cur_env}" ] && cur_env=1

local_cluster()
{
	local _jails=$( jorder )
	local _bhyve=$( border )
	local _qemu=$( qorder )
	local _xen=$( xorder )
	local _total_env=0
	local _cur_env=0
	local _json_files=

	[ -z "${JQ_CMD}" ] && JQ_CMD=$( which jq )
	[ -z "${JQ_CMD}" ] && err 1 "${N1_COLOR}${CBSD_APP} error: jq in requred${N0_COLOR}"

	for i in ${_jails} ${_bhyve} ${_qemu} ${_xen}; do
		_total_env=$(( _total_env + 1 ))
	done
#${CAT_CMD} <<EOF
#{
#  "servers":
#EOF
	_json_files=

	if [ ${_total_env} -ne 0 ]; then

		for i in ${_jails} ${_bhyve} ${_qemu} ${_xen}; do
			[ ! -r "${jailsysdir}/${i}/stats.json" ] && save-jail-info jname=${i}
			if [ -r "${jailsysdir}/${i}/stats.json" ]; then
				_json_files="${_json_files} ${jailsysdir}/${i}/stats.json"
			fi
		done

		${CAT_CMD} ${_json_files} | ${JQ_CMD} -s 'flatten' > /tmp/servers.json.$$
	else
		echo '{}' > /tmp/servers.json.$$
	fi

${CAT_CMD} > /tmp/clusters.json.$$ <<EOF
  {
    "total_environment": ${_total_env},
    "total_cpus": 6,
    "total_ram_bytes": 3221225472,
    "total_ram": "3 Gb",
    "total_imgsize_bytes": 32212254720,
    "total_imgsize": "30 Gb"
  }
EOF

	${CAT_CMD} /tmp/servers.json.$$ | jq '{ servers: . }' > /tmp/servers1.json.$$
	${CAT_CMD} /tmp/clusters.json.$$ | jq '{ clusters: . }' > /tmp/clusters1.json.$$
	${JQ_CMD} -s '.[0] * .[1]' /tmp/servers1.json.$$ /tmp/clusters1.json.$$

	${RM_CMD} -f /tmp/servers.json.$$ /tmp/clusters.json.$$ /tmp/servers1.json.$$ /tmp/clusters1.json.$$
}

# init CBSDfile data
if [ -n "${cwd}" ]; then
	if [ ! -r ${cwd}/CBSDfile ]; then
		local_cluster
		exit 0
	fi
	cbsdfile="${cwd}/CBSDfile"
	cd ${cwd}
fi

if [ -z "${cbsdfile}" -a ! -r "${CBSD_PWD}/CBSDfile" ]; then
	local_cluster
	exit 0
fi
. ${subrdir}/cbsdfile.subr

. ${subrdir}/time.subr

cluster_status()
{
	local CURL_CMD=$( which curl )
	local _cid

	[ -z "${CURL_CMD}" ] && err 1 "${N1_COLOR}cloud up requires curl, please install: ${N2_COLOR}pkg install -y curl${N0_COLOR}"
	[ -z "${CBSDFILE_RECURSIVE}" ] && ${ECHO} "${N1_COLOR}main cloud api: ${N2_COLOR}${CLOUD_URL}${N0_COLOR}" 1>&2
	_cid=$( ${miscdir}/cbsd_md5 "${CLOUD_KEY}" )
	# drop privileges to nobody
	${SU_CMD} -m nobody -c "${CURL_CMD} --no-progress-meter -H \"cid:${_cid}\" ${CLOUD_URL}/api/v1/cluster"
}

[ -z "${CLOUD_URL}" ] && err 1 "${N1_COLOR}${CBSD_APP}: empty CLOUD_URL${N0_COLOR}"
[ -z "${CLOUD_KEY}" ] && err 1 "${N1_COLOR}${CBSD_APP}: empty CLOUD_KEY${N0_COLOR}"

cluster_status

exit 0
