#!/usr/bin/env python
# -*- mode: python -*- $Id: ssdebug,v 1.5 2007/02/06 02:16:53 wangd Exp $
import os, sys
import cgitb
import cgi

cgitb.enable()
sys.stderr = sys.stdout
# use my own ssdap path
sys.path.append("/home/wangd/ssdapSpace/nco/src/ssdap")
# hack in the db path for now:
#dbfilename = None
dbfilename = "/dev/shm/ssdap_ram.sqlite"

class SsdInterface:
    def __init__(self):
        self.actions = {"rebuilddb": self.rebuildDb,
                        "showdb": self.showDb,
                        "help": self.printHelp,
                        "ls" : self.listFiles,
                        "env" : self.showEnv,
                        "filedb" : self.showFileDb }
    def buildUrl(self, action):
        # host, portnum, scriptpath,command
        template = "http://%s:%s%s?action=%s"
        return template % (os.environ["SERVER_NAME"],
                           str(os.environ["SERVER_PORT"]),
                           os.environ["SCRIPT_NAME"],
                           action)
    def handyHeader(self):
        pre = '<span id="toolbar"> Handy Toolbar: '
        bulk = ' | '.join(map( lambda x : '<a href="%s">%s</a>' 
                               % (self.buildUrl(x),x), self.actions.keys()))
        post = '</span>'
        return "".join([pre,bulk,post])
    def rebuildDb(self,form):
        """resets the db, clearing entries and using the latest schema"""
        import swamp_dbutil
        print self.handyHeader()
        print "dbfilename is ", dbfilename
        try:
            swamp_dbutil.deleteTables(dbfilename)
        except:
            pass # ok if error deleting tables.
        swamp_dbutil.buildTables(dbfilename)
        
        return "Done rebuilding db"
    def showDb(self,form):
        """prints the db state"""
        import swamp_dbutil
        print self.handyHeader()
        swamp_dbutil.quickShow(dbfilename)
        
        return "done with output"
    def showFileDb(self, form):
        """prints the filestate in the db"""
        import swamp_dbutil
        print self.handyHeader()
        swamp_dbutil.fileShow(dbfilename)
        return "done with output"
    def printHelp(self,form):
        """prints a brief help message showing available commands"""
        print self.handyHeader()
        print "<pre>available commands:"
        for a in self.actions:
            print "%-20s : %s" %(a, self.actions[a].func_doc)
        print "</pre>"
        
        return "done with output"
    def showEnv(self, form):
        """prints the cgi script's available env vars"""
        print self.handyHeader()
        for k in os.environ:
            print "%-20s : %s" %(k,os.environ[k])
        print "</pre>"
        return "done printing env"
    def listFiles(self,form):
        """does a normal ls file listing. sorta-secure"""
        print self.handyHeader()
        if not form.has_key("path"):
            print "no path specified, specify with parameter 'path'"
            return
        path = form.getvalue("path").strip()
        if path.startswith("/") or path.startswith("../") \
           or (path.find("..") > -1):
            print "invalid path specified, try again"
            return
        ppath = os.path.join(os.getenv("DOCUMENT_ROOT"),path)
        print "<pre>BEGIN listing for :",path
        #no leading /
        try:
            for a in os.listdir(ppath):
                print a
        except OSError:
            print "END Error using path ", path
        print "END listing</pre>"
        
        return "done with output"
        

    def execute(self, action, form, errorfunc):
        if action in self.actions:
            return self.actions[action](form)
        else:
            errorfunc()
            
class External:
    def printHeader(self):
        print "Content-type: text/html"
        print 
        print "<html><head><title>simple ssdap serverside</title></head>"
        print "<h1></h1>"
        print "<P>Hello, swamp serverside debugger!</p>"
    def parseParams(self):
        self.form = cgi.FieldStorage()
    def complain(self):
        print "<h2>Error: unsupported request</h2>"
    def execute(self):
        s = SsdInterface()
        if self.form.has_key("action"):
            action = self.form.getvalue("action")
            print "<pre>"
            output = s.execute(action, self.form, self.complain)
            if output == None:
                print "Action", action, " returned nothing"
            else:
                print output
            print "</pre>"
        else:
            print s.execute("help",{},self.complain)
            self.complain()
    def close(self):
        print "\n</body></html>\n"


e = External()
e.printHeader()
e.parseParams()
e.execute()
e.close()

