#!/bin/sh
#################################################################
#
# Parameters understood:
#
# 	config   (required)
# 	autoconf (optional - used by munin-config)
#
#################################################################


#################################################################
#################################################################
# Settigs required for autoconf
#%# family=manual
#%# capabilities=autoconf



if [ "$1" = "autoconf" ]; then
	echo no
	exit 0
fi

if [ "$1" = "config" ]; then

        echo 'graph_title CPU time per process '
        echo 'graph_args -l 0'
        echo 'graph_category system'
        echo 'graph_info This graph shows per cpu time for each top level process.'
	echo 'graph_vlabel Kbytes per ${graph_period}'

	first=0
	for proc in $((for pid in $(pgrep -P 1); do cat /proc/$pid/stat | sed -e 's/.*(\(.*\)).*/\1/g'; done;) | sort -u); do
		metricname=$(echo $proc | sed -e 's/[-_.]//g')
		commandline=$proc
		#echo $metricname $site
		echo $metricname'.label '$commandline
		echo $metricname'.info CPU for '$commandline'.'
		echo $metricname'.min 0'
		echo $metricname'.type DERIVE'
		if [ $first -eq 0 ]; then
			echo $metricname'.draw AREA'
		else
                        echo $metricname'.draw STACK'
		fi
		first=1
	done;
	exit 0
fi


#################################################################
# run the sript
	(for pid in $(pgrep -P 1); do
		metricname=$(cat /proc/$pid/stat | sed -e 's/.*(\(.*\)).*/\1/g' | sed -e 's/[-_.]//g')
		echo -n $metricname
		(for p in $(pgrep -P $pid; echo $pid); do cat /proc/$p/stat | awk '{ print $14 " " $16 " " $15 " " $17}'; done;) | awk '{ sum1 += $1; sum2 += $2; sum3 += $3; sum4 += $4; } END { print ( ".value " sum1 + sum2 + sum3 + sum4 ) }'
	done;) |sort | (aa=0; sumb=0; while read a b; do aa=$a; if [ "" == "$olda" ]; then olda=$a; fi; if [ "$a" != "$olda" ]; then echo $olda" "$sumb; olda=$a; sumb=0; fi; sumb=$(expr $sumb + $b); done; echo $aa" "$sumb;)


exit 0

# end of file
