#!/usr/bin/env python
#==============================================================
#
#  Abs:  A tool to checkout an EPICS package and build the 
#  package's RELEASE_SITE file. RELEASE_SITE is read by
#  configure/RELEASE to fill in versions of dependent releases
#  with the aim that no changes to configure/RELEASE are needed 
#
#  Name: eco
#
#  Facility:  SLAC/LCLS
#
#  Auth: 29-Nov-2010, Dayle Kotturi       (dayle)
#  Auth: 04-Nov-2011, Murali Shankar      (mshankar)
#  Rev:  dd-mmm-yyyy, Reviewer's Name     (USERNAME)
#
#  Requested features to be added:
#   - Add setting of directory permissions per new acl list changes; 
#     i.e. set a flag to lock them
#   - Only put IOC_SITE_TOP in RELEASE_SITE if actually needed, not just
#     generically
#   - Make use of "cvs rlog" command to show user all the possible tags
#   - Make it runnable with command line args or a file instead of terminal 
#     input; this includes making it checkout multiple packages at a time
#   - Break it into two scripts: one just to create the RELEASE_SITE file 
#     so that it could be used when checkout has already been done
#   - Make it work for subversion
#   - Make it go and change the $IOC/*/startup.cmd files to new release 
#       for all/subset of iocs in checked out app?s iocBoot
#
#--------------------------------------------------------------
#  Mod:
#  09-Dec-2010, Dayle Kotturi
#    Bring in defaults for each setting from the environmens
#  14-Dec-2010, Dayle Kotturi
#    Add EPICS_BASE_VER to entries in RELEASE_SITE; 
#    Use env var by same name as default 
#    If the HEAD is checked out, name the directory MAIN_TRUNK
#  15-Dec-2010, Dayle Kotturi
#    Add this header of comments
#    Add WWW_DIR to entries in RELEASE_SITE;
#    Use /afs/slac/www/grp/lcls as the default for WWW_DIR 
#    Change default for WWW_DIR to env var LCLS_WWW
#    Add capability to accept a file of 'package tag' pairs, 
#    one per line to do checkout with default env vars
#  04-Nov-2011 Murali Shankar
#    Removed all references to LCLS_WWW or WWW per Ernest
#  06-Dec-2011 Murali Shankar
#    Restored this version from CVS. Ernest wants me to update instead.
#  23-Feb-2012 Murali Shankar
#    Removed leading and trailing whitespace from inputs per Suzie and Ernest's request
#  04-June-2012 Murali Shankar
#    Updated the help per Ernest
#  04-June-2012 Murali Shankar
#    Added support for the -m modulename argument per Ernest
#  25-Sept-2012 Murali Shankar
#    Added a -P argument to cvs checkout per Ernest
#  13-Aug-2013 Murali Shankar
#    Support for PACKAGE_SITE_TOP; default value for this comes from PACKAGE_TOP per Ernest/Sonya
#  10-Oct-2013 Murali Shankar
#    Added support for BUILD_TARGETS using CROSS_COMPILER_TARGET_ARCHS in ${EPICS_BASE_RELEASE}/config/CONFIG_SITE and ${EPICS_BASE_RELEASE}/bin
#  12-Dec-2013 Murali Shankar
#    Pulled support for BUILD_TARGETS per Ernest as this generates fake conflicts with base's checkRelease
#  08-Jan-2014 Murali Shankar
#    Added support for specifying destination folder when using eco in interactive mode.
#  11-Feb-2014 Murali Shankar
#    Bug fix for specifying destination folder when using eco - the final cd was not using the correct variable - hence exception.
#  26-Aug-2014 Murali Shankar
#    Added support for TOOLS_SITE_TOP and ALARM_CONFIGS_TOP for Kristi
#  28-Jul-2015 Murali Shankar
#    Added a validation method to make sure folks have their enviroment variables set correctly.
#==============================================================
import sys
import os
import socket
import subprocess
import optparse
import readline
import shutil
import tempfile
import json
from ecogitutils import *



__all__ = ['export_release_site_file', 'assemble_release_site_inputs_from_file','assemble_cvs_inputs_from_file', 'assemble_release_site_inputs_from_term', 'assemble_cvs_inputs_from_term']


def parseGitModulesTxt():
    '''Parse the GIT modules txt file and return a dict of packageName -> location'''
    package2Location = {}
    gitModulesTxtFile = os.path.join(os.environ['TOOLS'], 'eco_modulelist', 'modulelist.txt')
    with open(gitModulesTxtFile, 'r') as f:
        lines = f.readlines()
    for line in lines:
        line = line.strip()
        if not line:
            continue
        if line.startswith('#'):
            continue
        parts = line.split()
        if(len(parts) < 2):
            print "Error parsing ", gitModulesTxtFile, "Cannot break", line, "into columns with enough fields using spaces/tabs"
            continue
        packageName = parts[0]
        packageLocation = parts[1]
        package2Location[packageName] = packageLocation
    return package2Location
        
def parseCVSModulesTxt():
    '''Parse the CVS modules file and return a dict of packageName -> location'''
    package2Location = {}
    cvsModulesTxtFile = os.path.join(os.environ['CVSROOT'], 'CVSROOT', 'modules')
    if not os.path.exists(cvsModulesTxtFile):
        print "Cannot determine CVS modules from modules file."
        return package2Location
    
    with open(cvsModulesTxtFile, 'r') as f:
        lines = f.readlines()
    for line in lines:
        line = line.strip()
        if not line:
            continue
        if line.startswith('#'):
            continue
        parts = line.split()
        if(len(parts) < 2):
            print "Error parsing ", cvsModulesTxtFile, "Cannot break", line, "into columns with enough fields using spaces/tabs"
            continue
        packageName = parts[0]
        packageLocation = parts[1]
        package2Location[packageName] = packageLocation
    return package2Location
        



git_package2Location = parseGitModulesTxt()
cvs_modules2Location = parseCVSModulesTxt()


def determine_archs():
    '''Determine the various architectures from ${EPICS_BASE_RELEASE}/configure/CONFIG_SITE:CROSS_COMPILER_TARGET_ARCHS and from folders in ${EPICS_BASE_RELEASE}/bin. We return a sorted list of archs'''
    lines = []
    with open(os.path.expandvars('${EPICS_BASE_RELEASE}/configure/CONFIG_SITE'), 'r') as f:
        lines = f.readlines()
    archs_from_config_site = [line for line in lines if line.startswith('CROSS_COMPILER_TARGET_ARCHS')][0].strip().split('=')[1].split(' ')
    archs_from_bin = os.listdir(os.path.expandvars('${EPICS_BASE_RELEASE}/bin'))

    total_archs = sorted(set(archs_from_config_site)|set(archs_from_bin))
    return total_archs


def export_release_site_file(inputs):
    """
    Use the contents of a dictionary of top level dirs to create a 
    RELEASE_SITE dir in a specified dir
    """

    #out_file = sys.stdout for testing 

    output_file_and_path = './RELEASE_SITE'
    try:
        out_file = open(output_file_and_path, 'w')
    except IOError, e:
        sys.stderr.write('Could not open "%s": %s\n' % (output_file_and_path, e.strerror))
        return None

    print >> out_file, '#=============================================================================='
    print >> out_file, '#RELEASE Location of external products'
    print >> out_file, '# Run "gnumake clean uninstall install" in the application'
    print >> out_file, '# top directory each time this file is changed.'
    print >> out_file, ''
    print >> out_file, '#=============================================================================='
    print >> out_file, '# Define the top of the EPICS tree for your site.'
    print >> out_file, '# We will build some tools/scripts that allow us to'
    print >> out_file, '# change this easily when relocating software.'
    print >> out_file, '#=============================================================================='
    print >> out_file, 'EPICS_SITE_TOP=%s'  % inputs['EPICS_SITE_TOP'] 
    print >> out_file, 'BASE_SITE_TOP=%s' % inputs['BASE_SITE_TOP']
    print >> out_file, 'MODULES_SITE_TOP=%s' % inputs['MODULES_SITE_TOP']
    print >> out_file, 'IOC_SITE_TOP=%s' % inputs['IOC_SITE_TOP']
    print >> out_file, 'EPICS_BASE_VER=%s' % inputs['EPICS_BASE_VER']
    print >> out_file, 'PACKAGE_SITE_TOP=%s' % inputs['PACKAGE_SITE_TOP']
    print >> out_file, 'TOOLS_SITE_TOP=%s' % inputs['TOOLS_SITE_TOP']
    print >> out_file, 'ALARM_CONFIGS_TOP=%s' % inputs['ALARM_CONFIGS_TOP']
    print >> out_file, '#=============================================================================='
    if out_file != sys.stdout:
        out_file.close()

    # change back to level where repo is
    os.chdir('../..')
    
def assemble_release_site_inputs_from_term():
    input_dict = {}

    prompt1 = 'Enter full path for EPICS_SITE_TOP or [RETURN] to use "'+os.getenv('EPICS_TOP')+'">'
    input_dict['EPICS_SITE_TOP'] = raw_input(prompt1).strip()
    if input_dict['EPICS_SITE_TOP'] == "":
        input_dict['EPICS_SITE_TOP'] = os.getenv('EPICS_TOP') # want something like, for eg, /usr/local/facet/epics    
    print 'Using ' + input_dict['EPICS_SITE_TOP']

    prompt2 = 'Enter full path for BASE_SITE_TOP or [RETURN] to use "'+os.getenv('EPICS_BASE_TOP')+'">'
    input_dict['BASE_SITE_TOP'] = raw_input(prompt2).strip()
    if input_dict['BASE_SITE_TOP'] == "":
        input_dict['BASE_SITE_TOP'] = os.getenv('EPICS_BASE_TOP') # want something like, for eg,  /usr/local/facet/epics/base
    print 'Using ' + input_dict['BASE_SITE_TOP']

    prompt3 = 'Enter full path for MODULES_SITE_TOP or [RETURN] to use "'+os.getenv('EPICS_MODULES_TOP')+'">'
    input_dict['MODULES_SITE_TOP'] = raw_input(prompt3).strip()
    if input_dict['MODULES_SITE_TOP'] == "":
        input_dict['MODULES_SITE_TOP'] = os.getenv('EPICS_MODULES_TOP') # want something like, for eg, /usr/local/facet/epics/modules/R3-14-8-2
    print 'Using ' + input_dict['MODULES_SITE_TOP']

    prompt4 = 'Enter full path for IOC_SITE_TOP or [RETURN] to use "'+os.getenv('EPICS_IOC_TOP')+'">'
    input_dict['IOC_SITE_TOP'] = raw_input(prompt4).strip()
    if input_dict['IOC_SITE_TOP'] == "":
        input_dict['IOC_SITE_TOP'] = os.getenv('EPICS_IOC_TOP') # want something like, for eg, /usr/local/facet/epics/iocTop
    print 'Using ' + input_dict['IOC_SITE_TOP']

    prompt5 = 'Enter full path for EPICS_BASE_VER or [RETURN] to use "'+os.getenv('EPICS_BASE_VER')+'">'
    input_dict['EPICS_BASE_VER'] = raw_input(prompt5).strip()
    if input_dict['EPICS_BASE_VER'] == "":
        input_dict['EPICS_BASE_VER'] = os.getenv('EPICS_BASE_VER') # want something like, for eg, base-R3-14-12
    print 'Using ' + input_dict['EPICS_BASE_VER']

    prompt6 = 'Enter full path for PACKAGE_SITE_TOP or [RETURN] to use "'+os.getenv('PACKAGE_TOP')+'">'
    input_dict['PACKAGE_SITE_TOP'] = raw_input(prompt6).strip()
    if input_dict['PACKAGE_SITE_TOP'] == "":
        input_dict['PACKAGE_SITE_TOP'] = os.getenv('PACKAGE_TOP')
    print 'Using ' + input_dict['PACKAGE_SITE_TOP']

    prompt6 = 'Enter full path for TOOLS_SITE_TOP or [RETURN] to use "'+os.getenv('TOOLS')+'">'
    input_dict['TOOLS_SITE_TOP'] = raw_input(prompt6).strip()
    if input_dict['TOOLS_SITE_TOP'] == "":
        input_dict['TOOLS_SITE_TOP'] = os.getenv('TOOLS')
    print 'Using ' + input_dict['TOOLS_SITE_TOP']

    prompt6 = 'Enter full path for ALARM_CONFIGS_TOP or [RETURN] to use "'+os.path.join(os.getenv('TOOLS'), 'AlarmConfigsTop')+'">'
    input_dict['ALARM_CONFIGS_TOP'] = raw_input(prompt6).strip()
    if input_dict['ALARM_CONFIGS_TOP'] == "":
        input_dict['ALARM_CONFIGS_TOP'] = os.path.join(os.getenv('TOOLS'), 'AlarmConfigsTop')
    print 'Using ' + input_dict['ALARM_CONFIGS_TOP']

    return input_dict


def assemble_release_site_inputs_from_file():
    input_dict = {}

    input_dict['EPICS_SITE_TOP'] = os.getenv('EPICS_TOP') # want something like, for eg, /usr/local/facet/epics    
    print 'Using ' + input_dict['EPICS_SITE_TOP']

    input_dict['BASE_SITE_TOP'] = os.getenv('EPICS_BASE_TOP') # want something like, for eg,  /usr/local/facet/epics/base
    print 'Using ' + input_dict['BASE_SITE_TOP']

    input_dict['MODULES_SITE_TOP'] = os.getenv('EPICS_MODULES_TOP') # want something like, for eg, /usr/local/facet/epics/modules/R3-14-8-2
    print 'Using ' + input_dict['MODULES_SITE_TOP']

    input_dict['IOC_SITE_TOP'] = os.getenv('EPICS_IOC_TOP') # want something like, for eg, /usr/local/facet/epics/iocTop
    print 'Using ' + input_dict['IOC_SITE_TOP']

    input_dict['EPICS_BASE_VER'] = os.getenv('EPICS_BASE_VER') # want something like, for eg, base-R3-14-12
    print 'Using ' + input_dict['EPICS_BASE_VER']

    input_dict['PACKAGE_SITE_TOP'] = os.getenv('PACKAGE_TOP')
    print 'Using ' + input_dict['PACKAGE_SITE_TOP']

    input_dict['TOOLS_SITE_TOP'] = os.getenv('TOOLS')
    print 'Using ' + input_dict['TOOLS_SITE_TOP']

    input_dict['ALARM_CONFIGS_TOP'] = os.path.join(os.getenv('TOOLS'), 'AlarmConfigsTop')
    print 'Using ' + input_dict['ALARM_CONFIGS_TOP']

    return input_dict

def validate_environment_settings():
    '''We use several environment variables as defaults. This method checks to make sure that these environment variables are set. 
    Its probably better to force the user to set these environment variables than to fight make at a later stage.'''
    needed_env_vars = ['EPICS_TOP', 'EPICS_BASE_TOP', 'EPICS_MODULES_TOP', 'EPICS_IOC_TOP', 'EPICS_BASE_VER', 'PACKAGE_TOP', 'TOOLS']
    for needed_env_var in needed_env_vars:
        if needed_env_var not in os.environ:
            print "The environment variable ", needed_env_var, "has not been defined. Did you remember to source the correct enviromnent script?"
            return False
    return True


# Determine the package and tag to checkout
def assemble_cvs_inputs_from_term(options):
    cvs_dict = {}

    cvs_dict['REPOSITORY'] = None

    if options.module:
        cvs_dict['REPOSITORY'] = options.module

    packageNames = set().union(git_package2Location.keys(), cvs_modules2Location.keys())
    def packageNameCompleter(text, state):
        options = [x for x in packageNames if x.startswith(text)]
        try:
            return options[state]
        except IndexError:
            return None

    readline.set_completer(packageNameCompleter)
    readline.parse_and_bind("tab: complete")

    while not cvs_dict['REPOSITORY']:
       cvs_dict['REPOSITORY'] = raw_input('Enter name of module/package to checkout: ').strip()

    # Remove completer after we are done...
    readline.set_completer()
    readline.set_completer_delims(" \t\n")
    readline.parse_and_bind('tab: self-insert')

    if hasattr(options, 'tag') and options.tag:
        cvs_dict['RELEASE'] = options.tag
    else:
        tags = []
        pathToGitRepo = determinePathToGitRepo(cvs_dict['REPOSITORY'])
        if pathToGitRepo:
            if os.path.exists(os.path.join(pathToGitRepo, "refs", "tags")):
                # Determine the list of tags..
                tags = os.listdir(os.path.join(pathToGitRepo, "refs", "tags"))
            else:
                print "Git repo at", pathToGitRepo, "does not seem to have any tags"
        else:
            p1 = subprocess.Popen(['cvs', '-Q', 'rlog', '-h', cvs_dict['REPOSITORY']], stdout=subprocess.PIPE)
            p2 = subprocess.Popen(['awk', '-F"[.:]"', '/^\t/&&$(NF-1)!=0{print $1}'], stdin=p1.stdout, stdout=subprocess.PIPE)
            p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
            output = p2.communicate()[0]

            plaintags = set()
            for line in output.split('\n'):
                line = line.strip()
                parts = line.split()
                if len(parts) < 1:
                    continue
                plaintags.add(parts[0].split(":")[0])
            tags = sorted(plaintags)

        if len(tags) > 0:            
            def tagCompleter(text, state):
                options = [x for x in tags if x.startswith(text)]
                try:
                    return options[state]
                except IndexError:
                    return None
            readline.set_completer(tagCompleter)
            readline.set_completer_delims(" \t\n")
            readline.parse_and_bind("tab: complete")
            
        prompt1 = 'Enter name of tag or [RETURN] to use HEAD>'
        cvs_dict['RELEASE'] = raw_input(prompt1).strip()
        if cvs_dict['RELEASE'] == "":
            cvs_dict['RELEASE'] = 'MAIN_TRUNK'

        readline.set_completer()
        readline.parse_and_bind('tab: self-insert')

    destinationFolder = cvs_dict['RELEASE']
    if options.destination:
        destinationFolder = options.destination
    print 'Using ' + cvs_dict['RELEASE'] + '. The name of the directory will be ' + destinationFolder + '.'
    
    checkOutModule(cvs_dict['REPOSITORY'], cvs_dict['RELEASE'], destinationFolder)

# Determine the package and tag to checkout
def assemble_cvs_inputs_from_file(repo, rel):
    cvs_dict = {}

    cvs_dict['REPOSITORY'] = repo
    cvs_dict['RELEASE'] = rel

    if cvs_dict['RELEASE'] == "" or cvs_dict['RELEASE'] == 'HEAD':
        cvs_dict['RELEASE'] = 'MAIN_TRUNK'
    print 'Using ' + cvs_dict['RELEASE'] + '. The name of the directory will be \'MAIN TRUNK\'.'

    # TO DO: does directory cvs_dict['REPOSITORY'] exist?

    if os.path.exists(cvs_dict['REPOSITORY']):
        print 'directory exists, just change directory there to do the checkout'
    else:
        #os.mkdir(path[, mode]) add mode if you want...
        os.mkdir(cvs_dict['REPOSITORY'])

    checkOutModule(cvs_dict['REPOSITORY'], cvs_dict['RELEASE'], cvs_dict['RELEASE'])
    
def checkOutModule(packageName, tag, destinationFolder):
    '''Checkout the module from GIT/CVS. 
    We first check to see if GIT has the module; if so, we clone the repo from git and do a headless checkout for the selected tag.
    Otherwise, we issue a command to CVS.
    '''
    if os.path.exists(packageName):
        print 'directory exists, just change directory there to do the checkout'
    else:
        os.mkdir(packageName)

    os.chdir(packageName)
    
    pathToGitRepo = determinePathToGitRepo(packageName)
    if pathToGitRepo:
        if pathToGitRepo.startswith("svn:///"):
            pathToSVNRepo =  pathToGitRepo.replace("svn:///", "file:///")
            if (tag == 'MAIN_TRUNK'):
                cmd='svn checkout ' + pathToSVNRepo + ' ' + destinationFolder    
                print cmd
            else:
                cmd='svn checkout --revision ' + tag + ' ' + pathToSVNRepo + ' ' + destinationFolder    
                print cmd
            os.system(cmd)
            os.chdir(destinationFolder)
        else:
            print packageName, "is a git package. Cloning the repository at", pathToGitRepo
            if os.path.exists(destinationFolder):
                print "The folder", os.path.abspath(destinationFolder), "already exists. If you intended to update the checkout, please do a git pull to pull in the latest changes."
                print "Aborting....."
                sys.exit(1)
            cmd=['git', 'clone', '--recursive', pathToGitRepo, destinationFolder]
            print cmd
            subprocess.check_call(cmd)
            os.chdir(destinationFolder)
            if (tag != 'MAIN_TRUNK'):
                # Do a headless checkout to the specified tag
                cmd=['git', 'checkout', tag]
                print cmd
                subprocess.check_call(cmd)
    else:
        if (tag == 'MAIN_TRUNK'):
            cmd='cvs checkout -P -d ' + destinationFolder + ' ' + packageName    
            print cmd
        else:
            cmd='cvs checkout -P -r '+ tag +' -d '+ destinationFolder +' ' + packageName    
            print cmd
        os.system(cmd)
        os.chdir(destinationFolder)

def determinePathToGitRepo(packageName):
    '''If the specified package is stored in GIT, then return the URL to the GIT repo. Otherwise, return None'''
    if packageName in git_package2Location:
        return git_package2Location[packageName]
    return None


def initGitBareRepo():
    '''Initialize a bare repo in the user specified folder'''
    gitRoot = determineGitRoot()
    
    # Ask the user for the name of the package
    packageName = subprocess.check_output(["zenity", "--entry", "--title", "Package Name", "--text", "Please enter the name of the package"]).strip()
    if packageName in git_package2Location or packageName in cvs_modules2Location:
        if packageName in git_package2Location:
            packageLocation = git_package2Location[packageName]
        elif packageName in cvs_modules2Location:
            packageLocation = os.path.join(os.environ['CVSROOT'], cvs_modules2Location[packageName])
        subprocess.check_call(["zenity", "--error", "--title", "Error", "--text", "The package " + packageName + " already is already registered and exists in " + packageLocation])
        return
    
    # Ask the use where the master repo is to be created
    bareRepoParentFolder = subprocess.check_output(["zenity", "--file-selection", "--title", "Please choose the parent folder where you want to create the bare repo", "--directory", "--filename="+gitRoot]).strip()
    
    apptype = determineCramAppType()

    # Create the master repo as a bare repo
    gitMasterRepo = initBareRepo(bareRepoParentFolder, packageName)
                                        
    tpath = tempfile.mkdtemp()
    curDir = os.getcwd()
    
    clonedFolder = cloneMasterRepo(gitMasterRepo, tpath, packageName)
    os.chdir(clonedFolder)
    
    createGitIgnore()
    createCramPackageInfo(packageName, apptype)
        
    commitAndPush()

    os.chdir(curDir)
    shutil.rmtree(tpath)
    
    addPackageToEcoModuleList(packageName, gitMasterRepo)
    
    print "Done creating bare repo for package ", packageName, ". Use eco to clone this repo into your working directory."
    subprocess.check_call(["zenity", "--info", "--title", "Repo created for " + packageName, "--text", "Done creating bare repo for package " + packageName + ". Use eco to clone this repo into your working directory."])


def importFromCVS():
    '''Import module from CVS and place into new git repo. Uses ${TOOLS}/cvs2git/current/cvs2git to do the actual importing'''
    gitRoot = determineGitRoot()
    checkCVS2GitPresent()
    
    # Ask the user for the name of the package
    packageName = subprocess.check_output(["zenity", "--entry", "--title", "Module Name", "--text", "Please enter the name of the module"]).strip()
    if packageName in git_package2Location:
        subprocess.check_call(["zenity", "--error", "--title", "Error", "--text", "The module " + packageName + " is already registered and exists here - " + packageLocation])
        return
    if packageName not in cvs_modules2Location:
        subprocess.check_call(["zenity", "--error", "--title", "Error", "--text", "The module " + packageName + " does not seem to be a CVS module."])
        return
    
    CVSpackageLocation = os.path.join(os.environ['CVSROOT'], cvs_modules2Location[packageName])
    print "Importing CVS module from ", CVSpackageLocation
    
    # Ask the use where the master repo is to be created
    bareRepoParentFolder = subprocess.check_output(["zenity", "--file-selection", "--title", "Please choose the parent folder where you want to create the bare repo", "--directory", "--filename="+gitRoot]).strip()
    
    # Create the master repo as a bare repo
    gitMasterRepo = initBareRepo(bareRepoParentFolder, packageName)     
                                   
    curDir = os.getcwd()
    tpath = tempfile.mkdtemp()

    importHistoryFromCVS(tpath, gitMasterRepo, CVSpackageLocation)
    
    clonedFolder = cloneMasterRepo(gitMasterRepo, tpath, packageName)
    os.chdir(clonedFolder)
    
    createGitIgnore()
    # We expect .cram/packageinfo to be there already
    
    commitAndPush()

    os.chdir(curDir)

    addPackageToEcoModuleList(packageName, gitMasterRepo)
    removeModuleFromCVS(tpath, packageName, CVSpackageLocation)

    os.chdir(curDir)
    shutil.rmtree(tpath)
    
    print "Done creating bare repo for package ", packageName, ". Use eco to clone this repo into your working directory."
    subprocess.check_call(["zenity", "--info", "--title", "Repo created for " + packageName, "--text", "Done creating bare repo for package " + packageName + ". Use eco to clone this repo into your working directory."])


def module_callback(option, opt_str, value, parser):
    print 'Processing MODULE option; Setting ', option.dest, ' to ', value
    setattr(parser.values, option.dest, value)
    if len(parser.rargs) > 0:
        print 'Setting tag to ' + parser.rargs[0]
        setattr(parser.values, 'tag', parser.rargs[0])
        parser.rargs.pop(0)
    else:
        print 'Defaulting tag to MAIN_TRUNK'
        setattr(parser.values, 'tag', 'MAIN_TRUNK')

def process_options(argv):
    if argv is None:
        argv = sys.argv[1:]

    usage = 'Usage: %prog <Command or File_listing_packages_and_tags (one pair per line)>\n'\
            + '\n'\
            + 'eco is a script that wraps git clone/cvs checkout and does some additional things that make compilation of modules within the EPICS/LCLS environment easier.\n'\
            + 'The main intent of eco is to get hardcoded paths out of configure/RELEASE.\n'\
            + 'It generates a file called RELEASE_SITE that contains these hardcoded paths; the configure/RELEASE now instead includes RELEASE_SITE\n'\
            + '\n'\
            + 'eco has interactive and batch modes.\n'\
            + 'To start eco in interactive mode, simply type eco\n'\
            + 'For the batch mode, you can pass in a file containing a list of the modules you want to checkout; for example, eco modulelist.txt.\n'\
            + 'Each line in this file contains the module name and the branch/tag label. \n'\
            + 'For example, a line for the sequencer would have "seq  seq-R2-0-11-lcls4"\n'\
            + '\n'\
            + 'eco also supports a command called initrepo "eco initrepo" that creates a bare git repository for your package.\n'\
            + '"eco initrepo" prompts you for a package name and type and repo location.\n'\
            + 'It then creates a bare git repo in the location specified; it also creates a default .gitignore and cram configuration for your package.\n'\
            + '\n'\
            + 'eco also supports a command called cvs2git "eco cvs2git" that imports a module from CVS into a git bare repo.\n'\
            + '"eco cvs2git" prompts you for a module name and type and repo location.\n'\
            + 'It then creates a bare git repo in the location specified; imports the history from CVS and adds a default .gitignore.\n'\
            + 'It comments out the module location in the CVSROOT/modules file; however, it does NOT do a cvs remove of the software from CVS.\n'\
            + '\n'
    version = '%prog 0.1'
    parser = optparse.OptionParser(usage=usage, version=version)

    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', help='print verbose output')
    parser.add_option('-m', '--module',  action='callback', dest='module', help='CVS module to checkout, optionally add the tag to use instead of MAIN_TRUNK', type='string', callback=module_callback)
    parser.add_option('-d', '--destination',  action='store', dest='destination', help='Checkout the package to this folder. Uses cvs -d. For example, eco -d CATER_12345 on MAIN_TRUNK checks out MAIN_TRUNK into a folder called CATER_12345. This option is ignored in batch mode.', type='string')
    # parser.add_option('-t', '--tag',  action='store', dest='tag', help='CVS tag to checkout - defaults to MAIN_TRUNK', type='string', default='MAIN_TRUNK')

    parser.set_defaults(verbose=False,
        db_file=None)

    (options, args) = parser.parse_args(argv)

    if len(args) == 1:
        options.input_file_path = os.path.normcase(args[0])
    else:
        options.input_file_path = None

    return options 

commands = {
    "initrepo" : initGitBareRepo,
    "cvs2git" : importFromCVS
}

def main(argv=None):
    options = process_options(argv)
    if not validate_environment_settings():
        return -1
    if (options.input_file_path):
        if options.input_file_path in commands:
            commands[options.input_file_path]()
            return
        try:
            in_file = open(options.input_file_path, 'r')
        except IOError, e:
            sys.stderr.write('Could not open "%s": %s\n' % (options.input_file_path, e.strerror))
            return None

        # Read in pairs (package release) one per line
        for line in in_file:
            # Remove comments
            line = line.partition('#')[0]

            # Turn 'a = b' into a key/value pair and remove leading and trailing whitespace
            (key, sep, value) = line.partition(' ')
            key = key.strip()
            value = value.strip()

            print 'key is: ' + key
            print 'value is: ' + value

            assemble_cvs_inputs_from_file(key,value)
            inputs = assemble_release_site_inputs_from_file()
            export_release_site_file(inputs)
           
            print 'done with ' + line
            # repeat above for all lines in file

        in_file.close()

    else:
        assemble_cvs_inputs_from_term(options)
        inputs = assemble_release_site_inputs_from_term()
        export_release_site_file(inputs)

    return 0
    

if __name__ == '__main__':
    status = main()
    sys.exit(status)
