#!/usr/bin/bash
#
# $0 --statusdir=<dir> <prefix> [<name> <item>]
#
STATUSDIR=/home/ngcomms/ngdata/inotify/smppd_status



function usage {
	cat <<-EOD

		SYNOPSIS

		    $(basename "$0") [--statusdir=/path/to/status/files] ( <discovery-prefix> |  <smppd-daemon-name> <item-key-name> )

		DESCRIPTION

		    Prints either a zabbix low-level-discovery (LLD) JSON structure representing
		    all running smppd daemons on this server, or when specified a specific item
		    key for a single specified smppd daemon (selected by name)

		OPTIONS

		    <discovery-prefix>  :=  An alphanumeric string to be prepended to all discovery key names
		                            eg, specifying 'Foo' would cause '{#PID}' to become {#Foo.PID}

		    <smppd-daemon-name> := Identities which specific daemon instance should be queried for the
		                           specified key (<item-key-name>)

		    <item-key-name>     := (NAME|TYPE|PID|STATE|TIMESTAMP)
		                           Selects which of the item key's values should be returned

	EOD
	exit 1
}





function discovery {
	local PREFIX="$1"

	# If we have a prefix, and it has no dot, then append one
	if [[ -n "$PREFIX" && "${PREFIX:(-1)}" != "." ]]; then
		PREFIX="${PREFIX}."
	fi

	# <pid>                                    <status>
	# |     <name>                 <type>      |      <date>     <time>
	# 7276 clx-transceiver-node1-1 transceiver online 2018-07-03 12:47:36
	echo "{ \"data\": ["
	while IFS='' read -r line || [[ -n "$line" ]]; do
		STATUS=( $line )
		PID="${STATUS[0]}"
		NAME="${STATUS[1]}"
		TYPE="${STATUS[2]}"
		STATE="${STATUS[3]}"
		TIMESTAMP="${STATUS[4]}T${STATUS[5]}"
		TIMESTAMP="$(date --date="${TIMESTAMP}" +%s)"

		echo "  { \"{#${PREFIX}NAME}\":\"$NAME\", \"{#${PREFIX}TYPE}\":\"$TYPE\", \"{#${PREFIX}STATE}\":\"$STATE\", \"{#${PREFIX}PID}\":\"$PID\", \"{#${PREFIX}TIMESTAMP}\":\"$TIMESTAMP\" },"

	done < <(find $STATUSDIR -maxdepth 1 -type f -print0 | xargs --null -r awk 'FNR==1 && NF==6{print}; FNR==2{exit;};')| sed -re '$ s/,[ \t]*$//'
	echo "] }"
}

function item {
	local NAME=$1
	local ITEM=$2
	local KEY=

	case "${ITEM,,}" in
		pid)       KEY=1;;
		name)      KEY=2;;
		type)      KEY=3;;
		state)     KEY=4;;
		timestamp) KEY=5;;
		*)
			echo "ERROR: Unknown key name $ITEM (Supported values are: name, type, pid, state, timestamp)" >&2
			echo 'ZBX_NOTSUPPORTED'
			exit 1
			;;
	esac

	# shellcheck disable=2016	
	RESULT=$(find "$STATUSDIR" -maxdepth 1 -type f -print0 \
	  | xargs --null -r  gawk \
	    -vRC=1 \
	    -vKEY="$KEY" \
	    -vNAME="$NAME" 'tolower($2) == tolower(NAME) { if (KEY == 5) { printf($5 " " $6); } else { printf($KEY); }; RC=0; exit; }; FNR==2{nextfile;}; END { exit RC; }')

	# shellcheck disable=SC2181
	if [ $? -eq 0 ]; then
		if [ $KEY -eq 5 ]; then
			date "--date=${RESULT}" +%s
		else
			echo "${RESULT}"
		fi
		exit 0
	else
		echo "ERROR: Requested daemon name '$NAME' not found" >&2
		echo "ZBX_NOTSUPPORTED"
	fi

}


# Handle optional statusdir
case "$1" in
	--statusdir=*) STATUSDIR="${1#--statusdir=}"; shift; ;;
	--statusdir) STATUSDIR="$2"; shift; shift; ;;
esac

if [ ! -d "${STATUSDIR}" ]; then
	echo "Invalid status directory '$STATUSDIR'" >&2
	echo "ZBX_NOTSUPPORTED"
	exit
fi


if [ $# -eq 1 ]; then
	discovery "$1"
elif [ $# -eq 2 ]; then
	item "$1" "$2"
else
	usage
fi






