#!/bin/bash
# History
# v1 - 20130501 - first very hacky version
# v2 - 20130502 - much more efficient version,
#	only makes one call to snmpget for each interface, and important 
#	params are in the plugin-conf.d/munin-node file
#
# See http://www.dd-wrt.com/phpBB2/viewtopic.php?p=753260 for 
# discussion and support
#
# gets dd-wrt wifi router ap stats
# add the followign to the plugin-conf.d/munin-node file:
#[wndr3800ifstats]
#env.ddwrthost my-dd-wrt-hostname-or-ip
#env.snmpcommunity public


MINIF=1
MAXIF=18

for X in `seq $MINIF $MAXIF`
do
	while read ifdescr inoctets outoctets inerrors outerrors indiscards outdiscards
	do
		#echo "$ifdescr $inoctets $outoctets $inerrors $outerrors $indiscards $outdiscards"

		IFNAME[$X]=$ifdescr
		IFNAMEX[$X]=`echo $ifdescr| sed 's/\./_/g'`
		IFERRORS[$X]=`expr $inerrors + $outerrors`
		IFDISCARDS[$X]=`expr $indiscards + $outdiscards`
		IFINKBITS[$X]=`expr $inoctets / 1000`
		IFOUTKBITS[$X]=`expr $outoctets / 1000`

	done < <(/usr/bin/snmpget -v 1 -c $snmpcommunity -O qv $ddwrthost IF-MIB::ifDescr.$X IF-MIB::ifInOctets.$X IF-MIB::ifOutOctets.$X IF-MIB::ifInErrors.$X IF-MIB::ifOutErrors.$X IF-MIB::ifInDiscards.$X IF-MIB::ifOutDiscards.$X | tr "\n\r" " " ; echo "" )
done

if [ "$1" = "config" ]; then
        echo "graph_title $HOST stats"
        echo 'graph_args --base 1000'
        echo 'graph_category network'
        echo "graph_info interface stats for the $HOST"

	for X in `seq $MINIF $MAXIF`
	do
		echo ${IFNAMEX[$X]}__in.label ${IFNAME[$X]} kbits in
		echo ${IFNAMEX[$X]}__in.type COUNTER

		echo ${IFNAMEX[$X]}__out.label ${IFNAME[$X]} kbits out
		echo ${IFNAMEX[$X]}__out.type COUNTER

		echo ${IFNAMEX[$X]}__errors.label ${IFNAME[$X]} errors
		echo ${IFNAMEX[$X]}__errors.type COUNTER

		echo ${IFNAMEX[$X]}__discards.label ${IFNAME[$X]} packets discarded
		echo ${IFNAMEX[$X]}__discards.type COUNTER
	done

	exit 0
fi


for X in `seq $MINIF $MAXIF`
do
	echo "${IFNAMEX[$X]}__in.value ${IFINKBITS[$X]}"
	echo "${IFNAMEX[$X]}__out.value ${IFOUTKBITS[$X]}"
	echo "${IFNAMEX[$X]}__errors.value ${IFERRORS[$X]}"
	echo "${IFNAMEX[$X]}__discards.value ${IFDISCARDS[$X]}"
done


# end
