#!/bin/bash

# netmon: the script used by netmon.wmi plugin.

# Based on the shell script found here:
# http://meinit.nl/shell-script-measure-network-throughput-linux-machines

# Usage: netmon [interface [scalefactor]]
#
# interface
#     The interface to monitor, default is eth0.
# scalefactor
#     The number equal the frequency of the updates.

readargs(){
if [ "$1" != "" ] ; then
    interface="$1"
else
    interface="eth0"
fi
if [ "$2" != "" ] ; then
    scalefactor=$2
else
    scalefactor=1
fi
}

if [ "`/sbin/ifconfig | grep 'RX bytes:'`" != "" ]
then
    ifconfig=old
else
    ifconfig=new
fi

printrxbytes(){
if [ "$ifconfig" == "old" ]
then
    /sbin/ifconfig "$interface" | grep "RX bytes" | cut -d: -f2 | awk '{ print $1 }'
else
    /sbin/ifconfig "$interface" | grep "RX packets" | awk '{ print $5 }'
fi
}

printtxbytes(){
if [ "$ifconfig" == "old" ]
then
    /sbin/ifconfig "$interface" | grep "TX bytes" | cut -d: -f3 | awk '{ print $1 }'
else
    /sbin/ifconfig "$interface" | grep "TX packets" | awk '{ print $5 }'
fi
}

bytestohumanreadable(){
multiplier="0"
number="$1"
number=$(($number/$scalefactor))
while [ "$number" -ge 1024 ] ; do
    multiplier=$(($multiplier+1))
    number=$(($number/1024))
done
while [ "$number" -ge 1000 ] ; do
    multiplier=$(($multiplier+1))
    number=$(($number/1000))
done
case "$multiplier" in
    1)
	echo "${number}K"
    ;;
    2)
	echo "${number}M"
    ;;
    3)
	echo "${number}G"
    ;;
    4)
	echo "${number}T"
    ;;
    *)
	echo "${number}B"
    ;;
esac
}

printresults(){
if [ -e $tempfile ] ; then
    . $tempfile
fi
if [ "$oldrxbytes" == "" ] ; then
    oldrxbytes=0
fi
if [ "$oldtxbytes" == "" ] ; then
    oldtxbytes=0
fi
rxbytes=$(printrxbytes)
txbytes=$(printtxbytes)
echo oldrxbytes="$rxbytes" > $tempfile
echo oldtxbytes="$txbytes" >> $tempfile
if [ "$oldrxbytes" -a "$rxbytes" -a "$oldtxbytes" -a "$txbytes" ] ; then
    echo "$interface RX = $(bytestohumanreadable $(($rxbytes - $oldrxbytes))) TX = $(bytestohumanreadable $(($txbytes - $oldtxbytes)))"
fi
}

counter="1"
readargs $1 $2
tempfile="$HOME/.wminfo/.netmon.$interface.tmp"
printresults

