#!/bin/sh
#
# Plugin to monitor CPU usage, for a selected set of processes. Tested on FreeBSD.
#
# Author: Erik Cederstrand
# Based on http://waste.mandragor.org/munin_tutorial/cpubyuser
# Thanks to Yann Hamon.
#
# Usage: Place in /usr/local/etc/munin/plugins/ (or link it there  using ln -s)
#        Add this to your /ur/local/etc/munin/plugin-conf.d/plugins.conf:
#       [cpubyproc]
#       env.procs httpd java
#
#    httpd and java being a list of the processes to monitor.

#
# Parameters understood:
#
#       config   (required)
#       autoconf (optional - used by munin-config)
#

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

procs=${procs:-}


if [ "$1" = "autoconf" ] ; then
    if [ -n "$procs" ] ; then
        echo "yes"
    else
        echo "no (environment variable 'procs' is not defined)"
    fi
    exit
fi

if [ "$1" = "config" ] ; then
    echo "graph_args --base 1000 -r --lower-limit 0"
    echo "graph_title CPU usage, by process"
    echo "graph_category processes"
    echo "graph_info This graph shows CPU usage, for monitored processes."
        echo 'graph_vlabel %'
        echo 'graph_scale no'
        echo 'graph_period second'

    echo "graph_order $procs"

    FIRSTPROC=1
    for proc in $procs; do
        echo "${proc}.label $proc"
        echo "${proc}.info CPU used by process $proc"
        echo "${proc}.type GAUGE"
        if [ $FIRSTPROC -eq 1 ] ; then
            echo "${proc}.draw AREA"
            export FIRSTPROC=0
        else
            echo "${proc}.draw STACK"
        fi
    done

    exit
fi



for proc in $procs ; do {

    ps axo 'pcpu,comm' | grep "$proc" | awk '
    BEGIN {
        FS=" "
        CPU_PROC=0
    }

    {
        CPU_PROC+=$0
    }

    END {
    print  "'"$proc"'.value "CPU_PROC
    }'
}

done
