#!/bin/bash
# -*- bash -*-

: << =cut

=head1 NAME

traffic - Plugin to monitor the traffic (throughput) by IP protocols.

=head1 CONFIGURATION

No special configuration is needed.

If trouble reading files, use:

 [traffic]
 user root

=head1 AUTHORS

=over

=item 2012.09.20: Initial version by Arturo Borrero Gonzalez <aborrero@cica.es>

=item 2013.01.12: Added percentage graphing by Michiel Holtkamp <michiel@supermind.nl>

=back

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

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

=cut


if [ "$1" == "config" ]
then
        cat <<'EOF'
multigraph traffic
graph_title Throughput by IP protocol
graph_vlabel bits per ${graph_period}
graph_category network
graph_args --base 1000 --upper-limit 100 -l 0
IPv4.label IPv4 bps
IPv4.min 0
IPv4.type DERIVE
IPv4.draw AREA
IPv6.label IPv6 bps
IPv6.min 0
IPv6.type DERIVE
IPv6.draw STACK
total.label Total bps
total.min 0
total.type DERIVE
total.draw LINE1
EOF

		# Adapted from http://munin-monitoring.org/wiki/PercentGraphHowto
		cat <<'EOF'
multigraph traffic_percent
graph_scale no
graph_title Throughput of IP protocols by percentage
graph_vlabel Percentage
graph_order IPv4=traffic.IPv4 IPv6=traffic.IPv6 total=traffic.total IPv4_percent=traffic.total IPv6_percent=traffic.total total_percent=traffic.total
graph_category network
graph_args --upper-limit 100 -l 0 -r
IPv4.label no
IPv6.label no
total.label no
total_percent.label no
IPv4.graph no
IPv6.graph no
total.graph no
total_percent.graph no
total_percent.cdef total,0.0000001,+
IPv4_percent.label IPv4
IPv4_percent.cdef IPv4,total_percent,/,100,*
IPv4_percent.draw AREASTACK
IPv6_percent.label IPv6
IPv6_percent.cdef IPv6,total_percent,/,100,*
IPv6_percent.draw AREASTACK
EOF
        exit 0
fi


if [ -r /proc/net/dev ]
then
	ipv4=$( echo "`egrep -v bond\|lo /proc/net/dev | awk -F' ' '{print $2+$10}' | paste -sd+ | bc` * 8" | bc )
	echo "IPv4.value $ipv4"
else
	echo "IPv4.value 0"
	echo "W: Unable to read /proc/net/dev" >&2
fi

if [ -r /proc/net/snmp6 ]
then
	ipv6=$( echo "`egrep Ip6InOctets\|Ip6OutOctets /proc/net/snmp6 | awk -F' ' '{print $2}' | paste -sd+ | bc` * 8"  | bc )
	echo "IPv6.value $ipv6"
else
	echo "IPv6.value 0"
	echo "W: Unable to read /proc/net/snmp6" >&2
fi
echo "total.value $( echo $ipv4 + $ipv6 | bc )"

exit 0

