#!/usr/bin/python
#
# This is the subcommand dispatcher. It and all the
# scripts below it are expected to vary with bocca release.

# impl notes:
# preconditions on calls made to subcommands:
# the script 'bocca' has been called and we have that
# environment defined.
# This is enforced.
# 
# Rules for this dispatcher (intended to make it scalable):
# sys.argv[0] will be the full path of this script always.
# sys.argv[1] will be a subcommand
# sys.argv[2:] will be subcommand options or arguments.
# all subcommands should take --help and -h as options
# all subcommands will be dispatched to the
# corresponding boccalib/ definition contained in 
# cct/$SUBCOMMAND.py.
import sys, os, imp, distutils.sysconfig
from cct._debug import DEBUGSTREAM

if not (os.environ.has_key('BOCCA_DEBUG')):
    print >> sys.stderr, "Direct use of cct not allowed. Use bocca."
    exit(2)

def dispatch(cmd, args):
    
    cmd = cmd.strip()
    cct_self = os.path.realpath(sys.argv[0])
    cct_dir = os.path.dirname(cct_self)
    
    libdirname = distutils.sysconfig.get_config_var('LIB')
    if libdirname is None: libdirname = 'lib' # for python versions < 2.5

    try:
        boccalibPath = os.path.abspath(os.path.join(cct_dir, '..', libdirname,
                                        'python' + distutils.sysconfig.get_python_version(), 
                                        'site-packages', 'boccalib'))
        cmdModulePath = os.path.join(boccalibPath, 'cct')
        sys.path.append(boccalibPath)
        sys.path.append(cmdModulePath)

        #sys.path.append(os.path.abspath(os.path.join(options.bocca_tools_bin, '..', getModulesDir())))
        print >> DEBUGSTREAM, 'cct module path (computed): ', cmdModulePath
    except:
        print 'cct: Cannot locate module path, will not be able to load subcommands'
        return 1
    
    if len(cmd) > 0:
        cmdModuleName = cmd.strip()
        cmdClassName = cmdModuleName.capitalize()
        #try:
        # No need to specify module path below since PYTHONPATH was set in the bocca dispatcher
        # to include the cct directory containing subcommands
        (file,filename,description) = imp.find_module(cmdModuleName,[cmdModulePath])
        mod = imp.load_module(cmdModuleName, file, filename, description)
        #result = menu[cmd](args, menu) 
        dir(mod)
        cmdClass = getattr(mod,cmdClassName)
        cmdClassInstance = cmdClass()
        cmdClassInstance.setModulePath(boccalibPath)
        result = cmdClassInstance.run(args)

#        except:
#            print "Error: Unknown bocca subcommand: ", cmd, ", Try the 'help' command."
#            result = 1
            
        return result
     
def main():

    if len(sys.argv) < 2:
        print sys.argv[0] , " requires an argument and should only be used by the internals of bocca"
        return 1
    cmd = sys.argv[1]
    args = sys.argv[2:]

    return dispatch(cmd, args)
     
    
class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

if __name__ == "__main__":
    sys.exit(main())
