#!/usr/bin/python
#
import readline
import getopt
import clump.db,ldap
from clump.cmd import *
from cmd import Cmd
import sys

class ClumpManager(Cmd):
    def __init__(self):
        Cmd.__init__(self)
        self.prompt="CLuMP%s> " % clump.db.db.dn2string()
        for key in registry.registry().keys():
            func="do_%s" % key
            helpfunc="help_%s" % key
            exec("def %s(self,line):\n" % func+
                 "    try:\n"+
                 "        registry.command('"+key+"').execute(line)\n"+
                 "    except SystemExit:\n"+
                 "        raise SystemExit\n"+
                 "    except ldap.INSUFFICIENT_ACCESS:\n"+
                 "        print '** ERROR ** Insufficient access to execute "+
                 "this command'\n"+
                 "#    except:\n"+
                 "#        print '** ERROR ** Command failed for "+
                 "unknown reasons!'\n"+
                 "def %s(self):\n" % helpfunc+
                 "    registry.command('"+key+"').help()\n")
            ClumpManager.__dict__[func]=eval(func)
            ClumpManager.__dict__[helpfunc]=eval(helpfunc)

    def help_help(self):
        print ("\nSyntax : HELP [<command>]\n"+
               "\n"+
               "Displays the list of commands understood by the CLuMP \n"+
               "manager program. More details about a given command can\n"+
               "be obtained by specifying it on the command line.\n")

    def do_EOF(self,line):
        print
        self.do_exit(line)

cfgfile="/etc/clump.conf"
opts,args=getopt.getopt(sys.argv[1:],"f:")
# Look for the configuration file command line option
for opt in opts:
    if opt[0]=="-f":      # Configuration file specification
        cfgfile=opt[1]
try:
    clump.db.db=clump.db.Connection(cfgfile)
except clump.db.ClumpConfigError,msg:
    print "** CONFIG ERROR ** %s" % msg
    sys.exit(1)

clump.db.prog=ClumpManager()

# See if there is a command to parse on the command line
if args:
    line=""
    for arg in args:
        line=line+"%s " % arg
    clump.db.prog.onecmd(line)
    sys.exit(0)
else:
    clump.db.prog.cmdloop("Welcome to the CLuMP manager program")
