#!/usr/bin/env python
import os
from optparse import OptionParser, OptionGroup, SUPPRESS_HELP




def createAlgorithmInfoFile(algInfoPath, algInfoTemplatePath, currentTime, revision, dbversion):
    from string import Template
    from time   import strftime

    try:
        algInfoFile = open(algInfoPath, 'w')
    except IOError, e:
        sys.stderr.write('Could not open "' + algInfoPath + '": ' + e.strerror + "\n")
        return 1

    algInfoTemplateFile = open(algInfoTemplatePath)
    algInfoTemplate = Template(algInfoTemplateFile.read())
    
    year  = str(currentTime[0])
    month = str(currentTime[1])
    day   = str(currentTime[2])
    
    print >> algInfoFile, algInfoTemplate.substitute(year      = year,
                                                     month     = month,
                                                     day       = day,
                                                     revision  = revision,
                                                     dbversion = dbversion)
                                                  
    algInfoFile.close()
    algInfoTemplateFile.close()
    
    return 0


def getDbList(databasePath):
    dblist = os.listdir(databasePath)    
    try:
        dblist.remove("CVS")
    except ValueError, e:
        pass
    
    for item in dblist:
        if not os.path.isdir(databasePath + "/" + item):
            dblist.remove(item)

    dblist.sort()
    
    return dblist


def listDatabaseVersions(databasePath):
    dblist = getDbList(databasePath)
    
    for item in dblist:
        print item

    return 0


def getNewestDbVersion(databasePath):
    dblist = getDbList(databasePath)
    count = len(dblist)
    if count is 0:
        newestDbVersion = ""
    else:
        newestDbVersion = dblist[count - 1]
    
    return newestDbVersion


def dbExists(databasePath, dbversion):
    dblist = getDbList(databasePath)
    try:
        dblist.index(dbversion)
    except ValueError, e:
        return False
    
    return True    


#---------------------------------------------------------------------
# Helper Functions
#---------------------------------------------------------------------

def nextChar(character):
    return chr(ord(character) + 1)


def makealgvrs(basepath = "."):
    from time import strftime, localtime
    currentTime       = localtime()
    currentTimeString = strftime("%Y-%m-%d", currentTime) + '-'
    revision          = 'a'
    algvrs            = currentTimeString + revision
    fullpath          = basepath + "/" + algvrs

    while os.path.lexists(fullpath):
        revision = nextChar(revision)
        algvrs   = currentTimeString + revision
        fullpath = basepath + "/" + algvrs

    return (algvrs, currentTime, revision)


def handleOptions():
    # Create parse options
    usage   = "Usage: %prog [options]"
                
    version = "%prog 1.0"
    parser = OptionParser(usage=usage, version=version)

    parser.add_option("-v", "--verbose",    action="store_true",            dest="verbose",                       help="Print verbose output.")
    parser.add_option("-l", "--listdbs",    action="store_true",            dest="listdbs",                       help="List databases")
    parser.add_option("-d", "--dbversion",  action="store",  type="string", dest="dbversion", metavar="DBVERS",   help="MPS Configuration DB to build against.  Default: newest database")
    parser.add_option("-o", "--outdir",     action="store", type="string",  dest="outdir",    metavar="DIR",      help="Parent output directory for new algorithm folder.  Default: .")
    
    # Defaults
    parser.set_defaults(verbose   = False,
                        listdbs   = False,
                        outdir    = ".",
                        dbversion = None,
                        algcom    = "../algorithmCommon/version0-0-2/baseAlgorithm",
                        dbdir     = "../database/")

    # Parse arguments
    (options, args) = parser.parse_args()    
    
    return (options, args)




#---------------------------------------------------------------------
# Main
#---------------------------------------------------------------------

def main():
    from shutil import copytree, Error
    from sys    import stderr
    
    # Options
    (options, args) = handleOptions()
    
    # List database versions
    if options.listdbs:
        return listDatabaseVersions(options.dbdir)

    # Get the DB version to build against
    dbversion = options.dbversion or getNewestDbVersion(options.dbdir)

    # Make a new algorithm folder
    outdir = options.outdir
    algcom = options.algcom
    (algvrs, currentTime, revision) = makealgvrs(outdir)
    
    outpath = os.path.normpath(outdir + "/" + algvrs)

    if os.path.lexists(outpath):
        stderr.write("Error: Output path \"%s\" already exists\n" % outpath)
        return 1
    
    if not os.path.lexists(algcom):
        stderr.write("Error: Source algorithm directory \"%s\" does not exist\n" % algcom)
        return 2

    # Copy the folder    
    if options.verbose:
        print "Copying source algorithm \"%s\"" % algcom
        print "to destination \"%s\"." % outpath

    try:
        copytree(algcom, outpath)
    except OSError, e:
        stderr.write("Could not copy \"%s\" to \"%s\": %s\n" % (algcom, outpath, e.strerror))
        return 1

    # Remove the CVS folders
    command = "find %r -name \"CVS\" -type d -exec rm -rf {} \;" % outpath
    os.popen4(command)
    
    # Create the algorithmInfo file
    if options.verbose:
        print "Writing AlgorithmInfo.txt file."

    algInfoTemplatePath = outpath + "/ReleaseTemplate.txt"
    algInfoFilePath     = outpath + "/configure/RELEASE"
    err = createAlgorithmInfoFile(algInfoFilePath, algInfoTemplatePath, currentTime, revision, dbversion)

    if err is not 0:
        return err
        
    # Remove AlgorithmInfoTemplate.txt
    os.remove(algInfoTemplatePath)
    
    # Verbose message
    if options.verbose:
        print "\nNew algorithm created at \"%s\"." % outpath

    if options.verbose and options.dbversion is None:
        print "Building algorithm against \"%s\".  You may want to edit the\nMPS_DATABASE_VERSION macro in \"%s\"." % (dbversion, algInfoFilePath)
    else:
        if not dbExists(options.dbdir, options.dbversion):
            print "Warning: MPS Config DB \"%s/%s\" does not exist.  You may want to edit the\nMPS_DATABASE_VERSION macro in \"%s\"." % (options.dbdir, dbversion, algInfoFilePath)


if __name__ == "__main__":
    main()

