#!/usr/bin/env bash

# ejabberd_stats_ revision 1 (Nov 2013)
#
# Tested with ejabberd 2.1.x
#
# This plugin is capable to show:
# - ejabberd connected users
# - in/out s2s connections
#
# Required permissions:
# - run ejabberdctl
#
# OS: *NIX
#
# Author: Artem Sheremet <dot.doom@gmail.com>
#
# Configuration:
# - set env.ejabberdctl to ejabberdctl path

#%# family=auto
#%# capabilities=autoconf suggest

EJABBERDCTL=${ejabberdctl:-$(which ejabberdctl)}
SCRIPT_NAME=$(basename $0)
STATS_TYPE="${SCRIPT_NAME/ejabberd_stats_/}"

function ejabberd_stats_connected_users() {
	local ejabberdctl_cmd=connected_users_number
	if [ "$1" = "config" ]; then
		cat <<CONFIG
graph_title ejabberd stats - connected users
graph_args --base 1000 --lower-limit 0
graph_vlabel users
graph_info The number of currently connected users, as of ejabberd report
graph_category chat 
graph_order active
connected.label Connected users
connected.draw AREA
connected.info ejabberdctl $ejabberdctl_cmd
CONFIG
	else
		echo "connected.value $($EJABBERDCTL $ejabberdctl_cmd)"
	fi
}

function ejabberd_stats_s2s() {
	local ejabberdctl_cmd_in=incoming_s2s_number
	local ejabberdctl_cmd_out=outgoing_s2s_number
	if [ "$1" = "config" ]; then
		cat <<CONFIG
graph_title ejabberd stats - s2s connections
graph_args --lower-limit 0
graph_vlabel active connections
graph_category chat
graph_order incoming outgoing
incoming.label incoming s2s
incoming.info ejabberdctl $ejabberdctl_cmd_in
outgoing.label outgoing s2s
outgoing.info ejabberdctl $ejabberdctl_cmd_out
CONFIG
	else
		cat <<RESULTS
incoming.value $($EJABBERDCTL $ejabberdctl_cmd_in)
outgoing.value $($EJABBERDCTL $ejabberdctl_cmd_out)
RESULTS
	fi
}

case $1 in
	autoconf)
		[ -x "$EJABBERDCTL" ] && echo yes || echo no
		exit 0
		;;
	suggest)
		cat <<SUGGESTIONS
connected_users
s2s
SUGGESTIONS
		exit 0
		;;
esac

ejabberd_stats_${STATS_TYPE} $1
