#!/bin/bash
#
#  Copyright (C) 2011-2016, it-novum GmbH <community@openattic.org>
#
#  openATTIC is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; version 2.
#
#  This package is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

set -e
set -u

if [ "$#" == "0" ] ; then
	echo "Usage: $0 <iface>" >&2
	exit 1
fi

for settings in "/etc/default/openattic" "/etc/sysconfig/openattic"
do
        [ -f $settings ] && . $settings
done

IFACE=$1
SYSFS="/sys/class/net/$IFACE"
IFSTATS="$NAGIOS_STATE_DIR/ifstats_$IFACE"

if [ ! -d "$SYSFS" ] ; then
	echo "Cannot access device information at $SYSFS" >&2
	exit 2
fi

if [ -f $IFSTATS ] ; then
	. $IFSTATS
else
	RXOLDBYTES=0
	TXOLDBYTES=0
	OLDTIMESTAMP=0
fi

STATE=`cat $SYSFS/operstate`
if [ "$STATE" != "up" ] ; then
	echo "Interface $IFACE is $STATE"
	exit 2
fi

NOW=`date +%s`

SPEED=`cat $SYSFS/speed 2>/dev/null || echo 0`
RXBYTES=`cat $SYSFS/statistics/rx_bytes`
TXBYTES=`cat $SYSFS/statistics/tx_bytes`

RXDIFF=`echo \( $RXBYTES - $RXOLDBYTES \) / \( $NOW - $OLDTIMESTAMP \) | bc`
TXDIFF=`echo \( $TXBYTES - $TXOLDBYTES \) / \( $NOW - $OLDTIMESTAMP \) | bc`

if [ "$SPEED" != "0" ]; then
	WARN=`echo $SPEED \* 0.75 \* 1000000 | bc`
	CRIT=`echo $SPEED \* 0.85 \* 1000000 | bc`
	
	# perfdata=cur;warn;crit;min;max
	echo "Interface $IFACE is $STATE ($SPEED MBit/s)|rxbytes=${RXDIFF}bytes/s;${WARN};${CRIT} txbytes=${TXDIFF}bytes/s;${WARN};${CRIT}"
else
	echo "Interface $IFACE is $STATE|rxbytes=${RXDIFF}bytes/s txbytes=${TXDIFF}bytes/s"
fi

cat >$IFSTATS <<EOF
RXOLDBYTES=$RXBYTES
TXOLDBYTES=$TXBYTES
OLDTIMESTAMP=$NOW
EOF
