#!/bin/sh
# -*- sh -*-
#
# Wildcard-plugin to monitor network interfaces. To monitor an
# interface, link if_<interface> to this file. E.g.
#
#    ln -s /usr/local/libexec/munin/plugins/if_ /etc/munin/plugins/if_em0
#
# ...will monitor em0.
#
# To aggregate all network interfaces on the system (except lo0),
# link if_aggregated to this file.
#
# Any device found in /usr/bin/netstat can be monitored.
#
# Magic markers (optional - used by munin-config and some installation
# scripts):
#
#%# family=auto
#%# capabilities=autoconf suggest

INTERFACE=${0##*if_}

if [ "$1" = "autoconf" ]; then
	if [ -x /sbin/ifconfig -o -x /usr/bin/netstat ]; then
		echo yes
		exit 0
	else
		echo "no (/usr/bin/netstat not found)"
		exit 0
	fi
fi

if [ "$1" = "suggest" ]; then
	if [ -x /sbin/ifconfig ]
	then
		ifconfig -l | sed -Ee 's/[[:<:]](pfsync|faith|pf(log|sync)|lo|plip|carp|enc|fwe)[^ ]*//g' | xargs -n 1 echo
		exit 0
	elif [ -x /usr/bin/netstat ]; then
		netstat -i -b -n | sed -n -e '/^faith/d' -e '/^lo[0-9]/d' -e '/^pf(log|sync)/d' -e '/<Link>/s/\** .*//p'
		exit 0
	else
		exit 1
	fi
fi

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

	echo "graph_order rbytes obytes"
	echo "graph_title $INTERFACE traffic"
	echo 'graph_args --base 1000'
	echo 'graph_vlabel bits per ${graph_period} in (-) / out (+)'
	echo 'graph_category network'
	echo "graph_info This graph shows the traffic of the $INTERFACE network interface. Please note that the traffic is shown in bits per second, not bytes."
	echo 'rbytes.label received'
        echo 'rbytes.type DERIVE'
        echo 'rbytes.graph no'
        echo 'rbytes.cdef rbytes,8,*'
	echo 'rbytes.min 0'
        echo 'obytes.label bps'
	echo 'obytes.type DERIVE'
	echo 'obytes.negative rbytes'
	echo 'obytes.cdef obytes,8,*'
	echo 'obytes.min 0'
	echo "obytes.info Traffic sent (+) and received (-) on the $INTERFACE network interface."
	exit 0
fi

if [ "$INTERFACE" = "aggregated" ]; then
	/usr/bin/netstat -i -b -n | grep -v '^lo' | awk '
BEGIN { rsum = 0; osum = 0; }
+/<Link>/ {
	if (NF == 5) {
		rsum += $4; osum += $5;
	} else if (NF == 6) {
		rsum += $5; osum += $6;
	} else if (NF == 11) {
		if ($4 ~ /:/) {
			rsum += $7; osum += $10;
		} else {
			rsum += $7; osum += $10;
		}
	} else { # NF == 12
		rsum += $5; osum += $6
	}
}
END {
	printf "rbytes.value %i\n", rsum;
	printf "obytes.value %i\n", osum;
}'

else
	/usr/bin/netstat -i -b -n -I $INTERFACE | awk '
/<Link>/ {
	if (NF == 5) {
		print "rbytes.value", $4;
		print "obytes.value", $5;
	} else  if (NF == 6) {
		print "rbytes.value", $5;
		print "obytes.value", $6;
	} else if (NF == 11) {
		if ($4 ~ /:/) {
			print "rbytes.value", $7;
			print "obytes.value", $10;
		} else {
			print "rbytes.value", $5;
			print "obytes.value", $6;
		}
	} else { # NF == 12
		print "rbytes.value", $8;
		print "obytes.value", $11;
	}
}'
fi

