#!@@GOODSH@@
#
# HP-UX port from original cpu plugin, here using sar instead of
# Solaris' kstat.  Also note that kstat as well as Linux /proc/stat
# use counters (of cpu cycles?), whereas sar merely displays
# percentages (hopefully this comes close enough)
#
# Customizations.  The values shown here are the defaults
#
#    [sar_cpu]
#        env.SYSWPCT 30     # System percentage to warn at
#        env.SYSCPCT 50     # System percentage where we're critical
#        env.USRWPCT 80     # User percentage to warn at
#        env.scaleto100 1   # Graph in percent rather than absolute ncpu
#
# Contributed by <ralph dot grothe at itdz minus berlin dot de>
#
#%# family=auto
#%# capabilities=autoconf

PATH=/usr/bin:/usr/sbin

if [[ $1 = autoconf ]]; then
    if uname -s|grep -qEi 'hp-?ux'; then
	echo yes
	exit 0
    else
	echo "no (This plugin is meant to be run under HP-UX)"
	exit 0
    fi
fi

: ${SYSWPCT:=30}
: ${SYSCPCT:=50}
: ${USRWPCT:=80}
: ${scaleto100:=1}

graphlimit=$percent
case $scaleto100 in (1|y*|Y*) graphlimit=100;; esac

if [[ $1 = config ]]; then
    typeset -i percent=100 ncpu=$(/usr/sbin/ioscan -kd processor|grep -c processor)
    (( $ncpu )) && ((percent*=ncpu))
    cpumax=$graphlimit

    # Indifferently carried over these crude threshold assumptions
    # from the original cpu plugin; should better be passed as envs
    # via plugins.conf

    syswarn=$(($cpumax*$SYSWPCT/100))
    syscrit=$(($cpumax*$SYSCPCT/100))
    usrwarn=$(($cpumax*$USRWPCT/100))

    echo 'graph_title CPU usage'
    echo 'graph_order system user waitio idle'
    echo 'graph_category CPU'
    echo "graph_args --base 1000 --lower-limit 0 --rigid --upper-limit $graphlimit"
    echo 'graph_vlabel %'
    echo 'graph_scale no'
    echo 'graph_period ${graph_period}'
    echo 'system.label system'
    echo 'system.draw AREA'
    echo 'system.type GAUGE'
    echo 'system.min 0'
    echo "system.max $cpumax"
    echo "system.warning $syswarn"
    echo "system.critical $syscrit"
    echo 'user.label user'
    echo 'user.draw STACK'
    echo 'user.type GAUGE'
    echo 'user.min 0'
    echo "user.max $cpumax"
    echo "user.warning $usrwarn"
    echo "waitio.max $cpumax"
    echo 'waitio.label waitio'
    echo 'waitio.draw STACK'
    echo 'waitio.type GAUGE'
    echo 'waitio.min 0'
    echo 'idle.label idle'
    echo 'idle.draw STACK'
    echo 'idle.type GAUGE'
    echo 'idle.min 0'
    echo "idle.max $cpumax"

    # this is kind of daft extrapolation to multi-cpu scaling from
    # sar's average

    if [[ $cpumax != 100 ]]; then
	echo "system.cdef system,$ncpu,*"
	echo "user.cdef user,$ncpu,*"
	echo "waitio.cdef waitio,$ncpu,*"
	echo "idle.cdef idle,$ncpu,*"
    fi
    exit 0
fi

sar -u 2 2 |\
awk '/verage/{printf"user.value %d\nsystem.value %d\nwaitio.value %d\nidle.value %d\n",$2,$3,$4,$5}'
