#!/bin/bash
# (C) 2009, Andrea Peluso.

expr $1 \+ 0 1> /dev/null
TEST=$?
if [ $# -ne 1 -o $TEST -ne 0 ]; then
  echo -e "Uso: $0 [limite in MB]\n"
  echo "Script di auto-disconnessione per abbonamenti a volume."
  echo -e "(C) 2009, Andrea Peluso.\n"
  exit 1
fi
DATE=$(date +%Y%m%d)
echo $DATE > /tmp/date.tmp
BYTEBU=0
LIM=$(expr $1 \* 1000000)
if [ -r /tmp/$DATE ]; then
  BYTEBU=`expr $(cat /tmp/$DATE)`
  if [ "$BYTEBU" -ge "$LIM" ]; then
    kdialog --warningcontinuecancel "Oggi sono gia' stati consumati $(expr $BYTEBU / 1000000) MB ($(expr $BYTEBU / 1048576) MB).\nVuoi continuare comunque?" --title "KillPPP"
    if [ $? = 0 ]; then
      exit 0
    else sudo killall pppd
    fi
  fi
  kdialog --msgbox "Oggi sono gia' stati consumati $(expr $BYTEBU / 1000000) MB ($(expr $BYTEBU / 1048576) MB).\nTraffico residuo: `expr \( $LIM \- $BYTEBU \) / 1000000` MB (`expr \( $LIM \- $BYTEBU \) / 1048576` MB)." --title "KillPPP" &
fi
while [ true ]
do
  RX=`cat /sys/class/net/ppp0/statistics/rx_bytes`
  TX=`cat /sys/class/net/ppp0/statistics/tx_bytes`
  BYTETOT=$(expr $RX \+ $TX \+ $BYTEBU)
  if [ "$BYTETOT" -ge "$LIM" ]; then
    echo + >> /tmp/$DATE
    cat /sys/class/net/ppp0/statistics/rx_bytes >> /tmp/$DATE
    echo + >> /tmp/$DATE
    cat /sys/class/net/ppp0/statistics/tx_bytes >> /tmp/$DATE
    kdialog --yesno "Sono stati consumati $(expr $BYTETOT / 1000000) MB ($(expr $BYTETOT / 1048576) MB).\nVuoi terminare la connessione?" --title "KillPPP"
    if [ $? = 0 ]; then
      sudo killall pppd
    fi
    exit 0
  fi
  sleep 5
done
