#!/bin/ash

[ -z "$inf" ] && exit 0
[ -z "$dir" -o ! -d "$dir" ] && exit 0
[ -d "/sys/class/net/$inf/statistics" ] || exit 0

[ -z "$ROOT" ] && ROOT=/www
SCRIPT=$ROOT/script

source $SCRIPT/utils/date.sh

cd "/sys/class/net/$inf"
echo -n "`cat operstate`" > "$dir/state"
echo -n "`cat speed 2>/dev/null`" > "$dir/speed"

cd "/sys/class/net/$inf/statistics"
txBytes="`cat tx_bytes`"
rxBytes="`cat rx_bytes`"
echo -n "`cat tx_packets`" > "$dir/txPackets"
echo -n "`cat rx_packets`" > "$dir/rxPackets"
echo -n "`cat tx_dropped`" > "$dir/txDropped"
echo -n "`cat rx_dropped`" > "$dir/rxDropped"

now=`nowAsUnixEpoch`
if [ -s "$dir/updatedAt" ] ; then
  oldTxBytes=`cat txBytes 2>/dev/null`
  oldRxBytes=`cat rxBytes 2>/dev/null`
  [ -z "$oldTxBytes" ] && oldTxBytes=0
  [ -z "$oldRxBytes" ] && oldRxBytes=0

  updatedAt="`cat $dir/updatedAt`"
  diff=$((now - updatedAt))

  txRate=$(((txBytes - oldTxBytes) / diff))
  rxRate=$(((rxBytes - oldRxBytes) / diff))
else
  txRate=0
  rxRate=0
fi

echo -n $now > "$dir/updatedAt"
echo -n $txBytes > "$dir/txBytes"
echo -n $rxBytes > "$dir/rxBytes"
echo -n $txRate > "$dir/txRate"
echo -n $rxRate > "$dir/rxRate"
