#!/bin/sh

INTERFACE=${0##*net_}

findspeed () {
    SPEED=10
    echo "up.max $SPEED"
    echo "up.info Traffic of the $INTERFACE interface. Maximum speed is $SPEED MiB."
    echo "down.max $SPEED"
}


case $1 in
    autoconf)
	if [ -r /proc/net/dev ]; then
	    echo yes
	    exit 0
	else
	    echo "no (/proc/net/dev not found)"
	    exit 0
	fi
	;;
    suggest)
	if [ -r /proc/net/dev ]; then
	    awk '
                /^ *(eth|tap|bond|wlan|ath|ra|sw|vlan|venet|veth|msh)[0-9]+(\.[0-9]+)?:/ {
                   split($0, a, /: */);
                   gsub(/^ +/,"",a[1]);
                   if (($2 > 0) || ($10 > 0)) print a[1]; }' /proc/net/dev
	fi
	exit 0
	;;
    config)
		       
	echo "graph_order down up" 
	echo "graph_title $INTERFACE traffic"
	echo 'graph_args --base 100'
	echo 'graph_vlabel MiB/s in (-) / out (+) per ${graph_period}'
	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. IMPORTANT: On 32 bit systems the data source for this plugin uses 32bit counters, which makes the plugin unreliable and unsuitable for most 100Mb (or faster) interfaces, where traffic is expected to exceed 50Mbps over a 5 minute period.  This means that this plugin is unsuitable for most 32 bit production environments. To avoid this problem, use the ip_ plugin instead.  There should be no problems on 64 bit systems running 64 bit kernels."
	echo 'down.label received'
        echo 'down.type DERIVE'
        echo 'down.graph no'
        echo 'down.cdef down,8,*'
	echo 'down.min 0'
        echo 'up.label MiB/s'
	echo 'up.type DERIVE'
	echo 'up.negative down'
	echo 'up.cdef up,8,*'
	echo 'up.min 0'

	findspeed

	exit 0
	;;
esac
# Escape dots in the interface name (eg. vlans) before using it as a regex
awk -v interface="$INTERFACE" \
    'BEGIN { gsub(/\./, "\\.", interface) } \
    $1 ~ "^" interface ":" {
        split($0, a, /: */); $0 = a[2]; \
        print "down.value " $1/(1024*1024) "\nup.value " $9/(1024*1024) \
    }' \
    /proc/net/dev

