#!/bin/bash
#
# This program fetches information from the kernels counters (which wraps
# around after 4GB of data), but avoids wrapping...
# You need to ensure this program is run more often then the counter wrap
# around (ie. by adding it to crontab every 10 minutes) or it will not be
# able to spot the wraps which will lead to incorrect calculations.
#
# ./pktcount.sh [devicename]

# default device name
DEV="onboard"

# directory to save counter information.
DBDIR="/home/gem/.netstats/"

# ------------------------------------- #

WRAPLIMIT="4294967296" # 2^32
STATSFILE="/proc/net/dev"
STATSDBTOTAL="${DBDIR}/total"
STATSDBLAST="${DBDIR}/last"

#set -x

if [ "$1" != "" ]; then
	DEV="$1"
fi

if [ ! -x "$DBDIR" ]; then
	echo "$DBDIR not found, aborting." >&2
	exit 1
fi

declare -a OLDTOTAL
declare -a LASTPKT

if [ -f "$STATSDBTOTAL" ]; then
	OLDTOTAL=($(cat "$STATSDBTOTAL"))
else
	OLDTOTAL=( 0 0 0 0 )
fi

if [ -f "$STATSDBLAST" ]; then
	LASTPKT=($(cat "$STATSDBLAST"))
else
	LASTPKT=( 0 0 0 0 )
fi

declare -a CURPKT
CURPKT=($(grep "$DEV:" $STATSFILE | cut -d: -f2 | awk "{print \$1 \" \" \$2 \" \" \$9 \" \" \$10}"))

declare -a NEWTOTAL

for i in 0 1 2 3; do
if [ "${LASTPKT[$i]}" -gt "${CURPKT[$i]}" ]; then
	echo "[$i] Packets wrapped."
	NEWTOTAL[$i]=$((${OLDTOTAL[$i]}+$WRAPLIMIT-${LASTPKT[$i]}+${CURPKT[$i]}))
else
	NEWTOTAL[$i]=$((${OLDTOTAL[$i]}+${CURPKT[$i]}-${LASTPKT[$i]}))
fi
done

echo "${CURPKT[*]}" > $STATSDBLAST
echo "${NEWTOTAL[*]}" > $STATSDBTOTAL

echo -e "Received\tbytes\t\tpackets"
echo -e "\t\t${NEWTOTAL[0]}\t${NEWTOTAL[1]}"
echo -e "Sent\t\tbytes\t\tpackets"
echo -e "\t\t${NEWTOTAL[2]}\t${NEWTOTAL[3]}"
