#!/usr/bin/python
#
# small script to get status-information from a T-com Sinus 1054 DSL
# and probably other T-com routers.
#
# Copyright (C) 2007 M G Berberich
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import sys, re, urllib

#
# print out usage on given descriptor or stderr
#
def usage(out = sys.stderr):
    print >> out, """dslstat command [router-ip]
information and set on-/offline tool for T-Com sinus 1054 DSL router
if router-ip is omitted it is set to 192.168.2.1

informational commands:
  status      prints full status-information, human readable
  state       prints online/offline-status
  gateway     prints IP-address of the WAN-gateway
  addr        prints WAN-IP-address of the DSL-router
  nameserver  prints first and second name-server 
  help        prints this list.
other commands
  online      tries to sets the router online and prints result
  offline     tries to sets the router offline and prints result

Copyright (C) 2007 by M G Berberich, GNU General Public License"""

#
# prints values in dict of key or list of key preceded by s
#
def printkey(s, dict, key):
    if not isinstance(key, list):
        key = [ key ]
    val = ""
    for k in key:
        if k in dict:
            val = " ".join((val, dict[k]))
    print "%s%s" % (s, val.lstrip())

#
# print on/off-line state
#
def printstate(s, dict):
    if "bWanConnected" in dict:
        if res["bWanConnected"] == "1":
            print "%sonline" % s
        else:
            print "%soffline" % s
    else:
        print "%sunknown" % s

#
# query router for status
#
def status_query(result, router_addr):
    try:
        sinus = urllib.urlopen("http://%s/hcti_status_ocontrol.htm" % 
                               router_addr)
    except:
        print >> sys.stderr, "Could not get status from \"%s\"" % router_addr
        sys.exit(2)
    p = re.compile("^var (.*)=(.*);$")
    for line in sinus:
        lm = re.match(p, line)
        if lm != None:
            id, val = lm.groups()
            val = val.strip('"')
            result[id] = val

#
# gets url from router,
# getting some special urls makes the router going on- or offline
#
def callrouter(router_addr, url):
    try:
        sinus = urllib.urlopen("http://%s/%s" % (router_addr, url))
    except:
        print >> sys.stderr, "Could not call \"%s\"" % router_addr
        sys.exit(2)

#
# main
#
if len(sys.argv) < 2 or len(sys.argv) > 3:
    usage()
    sys.exit(1)

command = sys.argv[1]
if len(sys.argv) == 3:
    router = sys.argv[2]
else:
    router = "192.168.2.1"

res = {}

if command == "status":
    status_query(res, router)
    print "Router-Status for", router
    printstate("State:       ", res)
    printkey("WAN IP:      ", res, "wan_ip")
    printkey("Nameserver:  ", res, ["primary_dns", "secondary_dns"])
    printkey("WAN Subnet:  ", res ,"wan_subnet_mask")
    printkey("WAN Gateway: ", res, "wan_gateway")

elif command == "state":
    status_query(res, router)
    printstate("", res)

elif command == "addr":
    status_query(res, router)
    printkey("", res, "wan_ip")

elif command == "gateway":
    status_query(res, router)
    printkey("", res , "wan_gateway")

elif command == "nameserver":
    status_query(res, router)
    printkey("", res, ["primary_dns", "secondary_dns"])

elif command == "online":
    callrouter(router, "cgi-bin/connect.exe")
    status_query(res, router)
    printstate("", res)
   
elif command == "offline":
    callrouter(router, "cgi-bin/disconnect.exe")
    status_query(res, router)
    printstate("", res)

elif command == "help":
    usage(sys.stdout)

else:
    usage()
    sys.exit(1)
