

import getopt
import sys, os, string


g_usageString = """Standard Staging Options:
-h: help
-d: debug
-k: Kill dest dirs before staging
--noOdl: Don't rebuild ODL files
--docs: Generate documentation
--quick: stage quick (now IDL or ODL compile)
--rootPyDir: Root dir for python files
--rootHtmlDir: Root dir for HTML file
--rootGeneratedDir:  Where generated stuff goes (ODL and IDL)
--generatedPackage: Subdir from gendir for gen code
"""


g_options = {}

g_args = []

g_commandLineParsed = 0

def GetPythonDir():
    return g_options['rootPyDir']

def GetSitePackagesDir():
    return GetPythonDir()+'/site-packages/'


def ParseCommandLine(shortOptions='hkd',longOptions=['quick','noOdl','docs','rootPyDir=','rootHtmlDir=','rootGeneratedDir=','generatedPackage='],usageString=g_usageString,defaults = {}):
    optList,args = getopt.getopt(sys.argv[1:],shortOptions,longOptions)

    global g_commandLineParsed
    if g_commandLineParsed:
        return

    g_commandLineParsed = 1

    unknownOpts = {}
    unknownArgs = []
    global g_options
    g_options['debug'] = 0
    g_options['quick'] = defaults.get('quick',0)
    g_options['kill'] = defaults.get('kill', 0)
    g_options['rootPyDir'] = defaults.get('rootPyDir',string.join(string.split(os.__dict__['__file__'],'/')[:-1],'/') + '/site-packages')
    g_options['xsltDir'] = defaults.get('xsltDir', '/usr/local/lib/xslt')
    g_options['rootHtmlDir'] = defaults.get('rootHtmlDir', '/home/httpd/html')
    g_options['rootGeneratedDir'] = defaults.get('rootGeneratedDir','/usr/local/lib/python')
    g_options['generatedPackage'] = defaults.get('generatedPackage', 'generated')
    g_options['noOdl'] = 0
    g_options['docs'] = 0

    for opt in optList:
        if opt[0] == '-h':
            PrintUsage(usageString)
            sys.exit()
        elif opt[0] == '-k':
            LogMessage("Enable option kill")
            g_options['kill'] = 1
        elif opt[0] == '-d':
            g_options['debug'] = 1
            LogMessage("Enable option debug")
        elif opt[0] == '--quick':
            LogMessage("Enable option quick")
            g_options['quick'] = 1
        elif opt[0] == '--noOdl':
            LogMessage("Disable ODS build")
            g_options['noOdl'] = 1
        elif opt[0] == '--docs':
            LogMessage("Enable Document generation")
            g_options['docs'] = 1
        elif opt[0] == '--rootPyDir':
            LogMessage("Set python root to %s" % opt[1])
            g_options['rootPyDir'] = opt[1]
        elif opt[0] == '--rootHtmlDir':
            LogMessage("Set html root to %s" % opt[1])
            g_options['rootHtmlDir'] = opt[1]
        elif opt[0] == '--rootGeneratedDir':
            LogMessage("Set generated root to %s" % opt[1])
            g_options['rootGeneratedDir'] = opt[1]
        elif opt[0] == '--rootGeneratedDir':
            LogMessage("Set generated package to %s" % opt[1])
            g_options['generatedPackage'] = opt[1]
        else:
            unknownOpts[opt[0]] = opt[1]
    unknwonArgs = args

    return unknownOpts,unknownArgs



def CreateDirTree(path, mode="775"):
    if type(path) == type([]):
        for p in path:
            CreateDirTree(p)
    else:
        if g_options['kill']:
            LogMessage("Remove Directory %s" % path)
            os.system('rm -rf %s' % path)
        LogMessage("Create Directory %s with mode %s" % (path,mode))
        os.system("install -d -m %s %s" % (mode,path))
    return


def CreateDirTreeFromPython(path,mode='775'):
    if type(path) == type([]):
        for p in path:
            CreateDirTree(GetPythonDir() + '/' + p)
    else:
        CreateDirTree(GetPythonDir() + '/' + path)
    return


def CreateDirTreeFromHtml(path,mode='775'):

    if type(path) == type([]):
        for p in path:
            CreateDirTree(g_options['rootHtmlDir'] + '/' + p)
    else:
        CreateDirTree(g_options['rootHtmlDir'] + '/' + path)
    return


def InstallFile(destDir,fileName,mode='664'):
    LogMessage("Install file %s to %s with mode %s" % (fileName,destDir,mode))
    os.system("cp %s %s" % (fileName,destDir))
    os.system("chmod %s %s/%s" % (mode,destDir,string.split(fileName,'/')[-1]))
    return


def CreateFile(filePath, mode='664'):
    LogMessage("Empty file %s to be created with mode %s" % (filePath, mode))
    os.system("touch " + filePath)
    os.system("chmod %s %s" % (mode, filePath))
    return


def CopyFiles(destDir,wcName='*.py',maxDepth=-1,srcDir = '.',mode = '664'):
    if sys.platform == 'sunos5':
        LogMessage("cd %s && cp -r %s %s" % (srcDir,wcName,destDir))
        LogMessage("cd %s && cp -r %s %s" % (srcDir,wcName,destDir))
        os.system("cd %s && cp -r %s %s" % (srcDir,wcName,destDir))
        os.system("cd %s && cp -r %s %s" % (srcDir,wcName,destDir))
    else:
        if maxDepth < 1:
            mdString = ""
        else:
            mdString = "-maxdepth %s" % maxDepth
        LogMessage("cd %s && find . -name '%s' %s -exec cp {} %s/{} \;" % (srcDir,wcName,mdString,destDir))
        LogMessage("cd %s && find . -name '%s' %s -exec chmod %s %s/{} \;" % (srcDir,wcName,mdString,mode,destDir))
        os.system("cd %s && find . -name '%s' %s -exec cp {} %s/{} \;" % (srcDir,wcName,mdString,destDir))
        os.system("cd %s && find . -name '%s' %s -exec chmod %s %s/{} \;" % (srcDir,wcName,mdString,mode,destDir))


#some higher level interfaces
def InstallPythonFiles(destDirExtension,maxDepth = -1,srcDir = '.',mode = '664'):
    CopyFiles(g_options['rootPyDir'] + '/' + destDirExtension,maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    return


def InstallHtmlFiles(destDirExtension,maxDepth = -1,srcDir = '.',mode = '664'):
    CopyFiles(g_options['rootHtmlDir'] + '/' + destDirExtension,wcName = '*.htm*',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    CopyFiles(g_options['rootHtmlDir'] + '/' + destDirExtension,wcName = '*.css*',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    return

    
def InstallImageFiles(destDirExtension,maxDepth = -1,srcDir = '.',mode = '664'):
    CopyFiles(g_options['rootHtmlDir'] + '/' + destDirExtension + '/images',wcName = '*.jpg',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    CopyFiles(g_options['rootHtmlDir'] + '/' + destDirExtension + '/images',wcName = '*.gif',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    return


def InstallRdfFiles(destDirExtension,maxDepth = -1,srcDir = '.',mode = '664'):
    CopyFiles(g_options['rootPyDir'] + '/' + destDirExtension,wcName = '*.rdf',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    return


def InstallOifFiles(destDirExtension,maxDepth = -1,srcDir = '.',mode = '664'):
    CopyFiles(g_options['rootPyDir'] + '/' + destDirExtension,wcName='*.oif',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    return


def InstallOdlFiles(destDirExtension,maxDepth = -1,srcDir = '.',mode = '664'):
    CopyFiles(g_options['rootPyDir'] + '/' + destDirExtension,wcName='*.odl',maxDepth = maxDepth,srcDir = srcDir,mode = mode)
    return


def InstallIdlFile(fileName):
    if g_options['quick']:
        return
    if not os.path.exists(g_options['rootGeneratedDir'] + '/' + g_options['generatedPackage']):
        CreateDirTree(g_options['rootGeneratedDir'] + '/' + g_options['generatedPackage'])
        CreateFile(g_options['rootGeneratedDir'] + '/' + g_options['generatedPackage'] + '/' + '__init__.py')


    InstallFile(g_options['rootGeneratedDir'] + '/' + g_options['generatedPackage'],fileName)
    os.system("cd %s/%s && omniidl -bpython %s" % (g_options['rootGeneratedDir'],g_options['generatedPackage'],os.path.split(fileName)[-1]))
    return


def InstallOdlFile(connectString,fileName,srcDir = '.',odlParseOptions = 'ifp'):
    if g_options['quick']:
        return
    if g_options['noOdl']:
        return
    CopyFiles(g_options['rootGeneratedDir'] + '/' + g_options['generatedPackage'],fileName,srcDir = srcDir)
    os.system("cd %s && OdlParse -%s %s %s" % (g_options['rootGeneratedDir'] + '/' + g_options['generatedPackage'],odlParseOptions,connectString,fileName))
    return


def VerifyCosName(name):
    names = string.split(name,'/')
    fullName = ''
    for n in names[:-1]:
        if fullName:
            fullName = fullName + '/' + n
        else:
            fullName = n
        if not os.popen('nameclt resolve %s' % fullName).read():
            if g_options['debug']:
                print 'nameclt bind_new_context %s' % fullName
            os.system('nameclt bind_new_context %s' % fullName)
    return


def VerifyCosNamePath(path):
    comps = string.split(path, '/')
    fullName = ''
    for comp in comps:
        if fullName:
            fullName = fullName + '/' + comp
        else:
            fullName = comp
        if not os.popen('nameclt resolve %s' % fullName).read():
            if g_options['debug']:
                print 'nameclt bind_new_context %s' % fullName
            os.system('nameclt bind_new_context %s' % fullName)
    return


def InstallParser(dirExt,parserDir,name,bgenOptions=''):
    CopyFiles(g_options['rootPyDir'] + '/' + dirExt,wcName='*.in')
    CopyFiles(g_options['rootPyDir'] + '/' + dirExt,wcName='Makefile')
    if g_options['quick']:
        return

    if bgenOptions:
        bgenOptions = '-' + bgenOptions

    LogMessage("Bulding %s Parser" % name)
    os.system('cd %s/%s/%s && BisonGen.py %s %s.bgen.in && make -sf Makefile.pre.in boot && make -s '% (g_options['rootPyDir'],dirExt,parserDir,bgenOptions,name))
    return


def InstallTransformedDocument(sourceFileName, stylesheetFileNames, outputFile,
                               topLevelParams=None):
    if g_options['quick'] and not g_options['docs']:
        return
    topLevelParams = topLevelParams or {}
    from xml.xslt.Processor import Processor
    from xml.xslt import XsltException
    processor = Processor()
    for fname in stylesheetFileNames:
        sty = g_options['xsltDir'] + '/' + fname
        processor.appendStylesheetFile(sty)
    result = processor.runUri(sourceFileName, 1, topLevelParams, 0)
    f = open(outputFile, 'w')
    f.write(result)
    f.close()
    return


def LogMessage(msg):
    if g_options['debug']:
        print msg

