#!/bin/bash

# dlinkppp - helper script for dlinkdsl-hosted
#   Gets the current ppp0 stats from a D-Link (or other Linux) router
#   Sets dlinkdsl-hosted's tooltip to the download/upload stats
#   Makes the icon blink if network is down

# Author: Alex Ibrado <alex@kdex.org>
# Part of the Konch distribution, http://konch.kdex.org/

### Don't forget to change the values in dlinkdsl.conf to match your setup ###

KONCH=$1

SDIR=`dirname $0`
SPATH=`(cd $SDIR; pwd)`

. $SPATH/dlinkdsl.conf

function tail_ppp {
  (
  echo $USER
  sleep 0.3
  echo $PASS
  sleep 0.3
  echo "watch -n 1 /bin/cat /proc/net/dev | grep ppp0"
  sleep 0.3
  while [ 1 ]; do
    sleep 1 
  done
  ) | nc -t $HOST $PORT 
}

LAST_IN=0
LAST_OUT=0
BLINK=0

function parse_speeds {
  IN=$1
  OUT=$9

  DELTA_IN=0
  DELTA_OUT=0

  if [ $LAST_IN -gt 0 ]; then
    let DELTA_IN=IN-LAST_IN
  fi

  if [ $LAST_OUT -gt 0 ]; then
    let DELTA_OUT=OUT-LAST_OUT
  fi

  DK_IN=`echo "scale=2 ; $DELTA_IN / 1024" | bc -l`
  DK_OUT=`echo "scale=2 ; $DELTA_OUT / 1024" | bc -l`

  echo dcop $KONCH Konch setTooltip "$DK_IN KBps / $DK_OUT KBps"
  dcop $KONCH Konch setTooltip "$DK_IN KBps / $DK_OUT KBps"

  if [ $BLINK -eq 0 -a $DELTA_IN -le 0 -a $DELTA_OUT -le 0 ]; then
    dcop $KONCH Konch blink 500
    BLINK=1
  elif [ $BLINK -eq 1 -a $DELTA_IN -gt 0 ]; then
    dcop $KONCH Konch blink 0
    BLINK=0
  fi

  LAST_IN=$IN
  LAST_OUT=$OUT
 
}

tail_ppp | while read LINE
  do
    PPP=`echo $LINE | grep ppp0: | cut -c6-`
    if [ "$PPP" != "" ]; then
      parse_speeds $PPP
    fi
  done 

