#!/bin/bash
#
# zyxel.sh
#
# Simple script to collect toneband information from a Zyxel P-2812HNU-F1 (only tested with
# 3.11 tue1 firmware on an ADSL2+ connection)
#
# 20120228 MV: Initial version
#

DB=/tmp/tones.db     # Path where the database should be created
MODEM=192.168.1.254  # The IP adres of your modem
LOGIN=admin          # The login name of a user
PASS=admin           # The password of the user
TMPFILE=/tmp/zyxel.$$
COOKIES=$TMPFILE.cookies
STATS=$TMPFILE.stats

getdata()
{
   if ! test -f $DB
   then
      echo "CREATE TABLE tones (date integer, tone integer, bits integer);" | sqlite3 $DB
   fi
   
   rm -f $COOKIES $STATS
   wget -q -O /dev/null --post-data="UserName=$LOGIN&password=$PASS&hiddenPassword=$PASS&submitValue=1" --save-cookies cookies --keep-session-cookies $COOKIES "http://$MODEM/login.cgi"
   wget -q -O $STATS --post-data="DiagDSLStatus=DSL+Line+Status&ResetADSLRetryTime=0" --load-cookies cookies --save-cookies cookies --keep-session-cookies $COOKIES "http://$MODEM/diagnostic.cgi"
   cat $STATS | awk 'BEGIN {time=systime();} /^\(/ { line=$0; start=10; while (index(line,"(") != 0) { start=index(line,"("); end=index(substr(line,start),")"); value=substr(line, start,end); sep=index(value,","); tone=substr(value,2,sep-2); bits=strtonum("0x"substr(value,sep+1,length(value)-sep-1));printf("INSERT INTO tones VALUES (%d,%d,%d);\n", time, tone, bits); line=substr(line, start + end); }}' | sqlite3 $DB
   rm -f $COOKIES $STATS
}

plot()
{
   for date in $( echo "select date from tones group by date;" | sqlite3 $DB )
   do
      echo "select * from tones where date=$date;" | sqlite3 -separator ' ' $DB
      echo
   done > $TMPFILE

   cat - > $TMPFILE.plot <<EOF
   set title "Tone bands"
   set xdata time
   set timefmt "%s"
   set format x "%d/%m/%Y %H:%M"
   set xlabel "Date"
   set ylabel "Tone band"
   set zlabel "Encoded bits"
   set zrange [0:16]
   set ytics nomirror
   set ytics autofreq
   splot "$TMPFILE" using 1:2:3 with lines
EOF
   gnuplot $TMPFILE.plot -
   rm -f $TMPFILE.plot
}

usage()
{
   echo "Usage: $0 <plot|getdata>"

}

main()
{
   case "$1" in
   "plot")
      plot
   ;;
   "getdata")
      getdata
   ;;
   *)
      usage
   ;;
   esac
}

main $*
