#!/bin/bash

# wminfo plugin: total incoming and outgoing traffic for selected interfaces

# command: wminfo -p traffic.wmi -u 5 -b#000000 -f#ff00ff

# Attention: traffic.wmi plugin uses traffic script
#            the command traffic.wmi -reset resets the traffic counters
#            the plugin resets the traffic counters after 999h 59m 59s

if [ "`which traffic 2> /dev/null`" == "" ]
then
    echo "$0: put traffic script into PATH."
    echo -e "         \n         \n         \n         \n"
    exit
fi

for interface in eth0 eth1
do
    LOGFILE="$HOME/.wminfo/.interface.$interface.log"
    /sbin/ifconfig $interface &> $LOGFILE
    if [ "`grep 'Device not found' $LOGFILE`" == "" ]
    then
	ETH=`traffic $interface $1`
	ETH_INT=$interface
    fi
done

for interface in wlan0 wlan1
do
    LOGFILE="$HOME/.wminfo/.interface.$interface.log"
    /sbin/ifconfig $interface &> $LOGFILE
    sleep 1
    if [ "`grep 'Device not found' $LOGFILE`" == "" ]
    then
	WLN=`traffic $interface $1`
	WLN_INT=$interface
    fi
done

ETH_RX="`echo $ETH | awk '{print $4}' | sed -E 's/([0-9]+)\.([0-9]).?(.)/\1.\2\3/'`"
ETH_TX="`echo $ETH | awk '{print $7}' | sed -E 's/([0-9]+)\.([0-9]).?(.)/\1.\2\3/'`"
WLN_RX="`echo $WLN | awk '{print $4}' | sed -E 's/([0-9]+)\.([0-9]).?(.)/\1.\2\3/'`"
WLN_TX="`echo $WLN | awk '{print $7}' | sed -E 's/([0-9]+)\.([0-9]).?(.)/\1.\2\3/'`"

datafile="$HOME/.wminfo/.traffic.old"

if [ "$1" == "-reset" ]
then
    > $datafile
    exit
fi

if [ ! -e $datafile ] || [ ! -s $datafile ]
then
    echo "olddate=`date +"%s"`" > $datafile
fi

. $datafile

newdate="`date +"%s"`"

let "datediff=$newdate-$olddate"

let hours="$datediff/3600"
let minutes="($datediff-$hours*3600)/60"
let seconds="$datediff-$hours*3600-$minutes*60"

if [ $hours -lt 10 ]
then
    hours="0$hours"
fi

if [ $minutes -lt 10 ]
then
    minutes="0$minutes"
fi

if [ $seconds -lt 10 ]
then
    seconds="0$seconds"
fi

if [ $hours -lt 1000 ]
then
    echo "$hours:$minutes:$seconds"
else
    > $datafile
    traffic $ETH_INT -reset 1>/dev/null
    traffic $WLN_INT -reset 1>/dev/null
    echo -e "         \n         \n         \n         \n         "
    exit
fi

echo "ETH $ETH_RX"
echo "ETH $ETH_TX"
echo "WLN $WLN_RX"
echo "WLN $WLN_TX"

echo -e "         \n         \n         \n         \n         "; 

