#!/usr/bin/bash
#
# Provides scheduler properties for S3EP resources.
# Run by shaman's schedule on the master and by shaman list-supported-roles.
#
# Provided environment variables:
# - PROPERTY_NAME - name of the property
# - NODE - node id, for count only
#

if [ -z "$PROPERTY_NAME" ]; then
	echo "PROPERTY_NAME environment variable undefined" 1>&2
	exit 1
fi

case "$PROPERTY_NAME" in
type)
	echo S3EP ;;
schedule-count)
	echo YES ;;
count)
	if [ -z "$NODE" ]; then
		echo "NODE environment variable undefined" 1>&2
		exit 1
	fi
	# The s3ep- resources shaman lists on NODE or is moving to it, or 0 when
	# shaman stat gives no answer within 2 s: schedule caches a count it can parse.
	/usr/bin/timeout 2 /usr/sbin/shaman stat --json 2>/dev/null |
		/usr/bin/jq -n --arg node "$NODE" \
		'input | [(.status.nodes[$node].resources // {} | keys[]),
			(.status.transition[$node] // {} | .[] | keys[])
			| select(startswith("s3ep-"))] | unique | length' \
		2>/dev/null || echo 0
	;;
*)
	;;
esac

exit 0
