#!/bin/bash
#
# Plugin to monitor Memory usage inspired by cpubyuser
#
# 2012-05-23 Sebastien Campion

LU=`ps auh | cut -d' ' -f 1  | sort -u`
USERS=`echo $LU`

if [ "$1" = "autoconf" ]; then
	if [ -n "$USERS" ]; then
		echo "yes"
	else
		echo "\$USERS not defined."
	fi
	exit
fi

if [ "$1" = "config" ]; then
	echo "graph_args --base 1000 -r --lower-limit 0"
	echo "graph_title Memory usage, by user"
	echo "graph_category memory"
	echo "graph_info This graph shows memory usage, for monitored users."
	echo "graph_vlabel KB"
	echo "graph_scale no"
	echo "graph_period second"
	_USERS=${USERS//[-.]/_}
	echo "graph_order $_USERS others"
	FIRSTUSER=1;
	for USER in $USERS "others"; do
		_USER=${USER//[-.]/_}
		echo "${_USER}.label $USER"
		echo "${_USER}.info Memory used by user $USER"
		echo "${_USER}.type GAUGE"
		if [ $FIRSTUSER -eq 1 ]; then
			echo "${_USER}.draw AREA"
			FIRSTUSER=0
		else
			echo "${_USER}.draw STACK"
		fi
	done
	exit
fi

ps -e -o "%z%U" | \
	awk -v USERS="$USERS" '
		{ if ($2 != "USER") MEM_USER[$2]+=$1 }
		END {
			others_sum = 0
			for (user in MEM_USER) {
				m = match(USERS,user)
				if (m != 0) {
					_user=user
					gsub(/[-.]/,"_", _user);
					print _user".value", MEM_USER[user]
				} else
					others_sum += MEM_USER[user]
			}
		print "others.value", others_sum;
	}'
