#! /usr/bin/env python
#  _________________________________________________________________________
#
#  PyUtilib: A Python utility library.
#  Copyright (c) 2008 Sandia Corporation.
#  This software is distributed under the BSD License.
#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
#  the U.S. Government retains certain rights in this software.
#  For more information, see the PyUtilib README.txt file.
#  _________________________________________________________________________
#
# This script creates a Python installer script.  Note that this script assumes that
# 'virtualenv' is installed in Python.
#

import os
import os.path
import re
import sys
import stat
import virtualenv

# The files that are integrated into a virtualenv installer
files = ['odict.py', 'OrderedConfigParser.py', 'header.py', 'wheels.py']

pyutilib_re = re.compile("(pyutilib[/\\\\]virtualenv[/\\\\].*)")

def vpy_create(config_name, script_name):
    try:
        virtualenv_ver = virtualenv.__version__.split('.')
        for i,v in enumerate(virtualenv_ver):
            try:
                virtualenv_ver[i] = int(v)
            except:
                pass
        virtualenv_ver = tuple(virtualenv_ver)
    except:
        # catch-all for __version__ failing or any other weirdness.
        virtualenv_ver = (0,0)
    if virtualenv_ver[:2] < (1,11):
        raise RuntimeError(
            "pyutilib.virtualenv.vpy_create() requires virtualenv>=1.11\n"
            "\tVirtualenv version %s was found.\n\tAborting." % 
            ( virtualenv.__version__, ) )

    here = os.path.dirname(os.path.abspath(__file__))
    source_files = []
    for f in files:
        source_files.append( os.path.join(here,f) )
    if config_name != 'vpy':
        source_files.append(config_name)

    new_text = "# PYUTILIB.VIRTUALENV - START\n"
    for f in source_files:
        m = pyutilib_re.search(f)
        if m:
            new_text += "\n#\n# Imported from " + m.group(0) + "\n#\n\n"
        else:
            new_text += "\n#\n# Imported from " + f + "\n#\n\n"
        INPUT = open(f,'r')
        new_text += "".join( INPUT.readlines() )
        INPUT.close()
        new_text += "\n"
    #new_text += "\n"
    #new_text += "Repository.easy_install_path='"+sys.prefix+os.sep+'bin'+os.sep+'easy_install'+"'"
    new_text += "\n# PYUTILIB.VIRTUALENV - END\n"

    new_text = virtualenv.create_bootstrap_script(new_text)
    tmp = []
    inHeader = True
    for line in new_text.split('\n'):
        if inHeader:
            if line[0] != "#":
                inHeader = False
                tmp.append("""#
# This virtualenv bootstrap script creates a virtual Python environment.
# It was generated by pyutilib.virtualenv.vpy_create() from the following 
# source files:""")
                for f in source_files:
                    # trim absolute path, if necessary
                    m = pyutilib_re.search(f)
                    if m:
                        tmp.append("#     " + m.group(0))
                    else:
                        tmp.append("#     " + f)
                tmp.append("""#     virtualenv.create_bootstrap_script()
#
# DO NOT MODIFY THIS FILE.
# Instead, modify the source files and regenerate this file with vpy_create()
#""")
        if 'win32api' in line:
            tmp.append( line[:line.index(line.strip())] + 'pass')
        #elif 'TODO' in line or 'FIXME' in line:
            #tmp.append( line[:line.index(line.strip())] + '# pyutilib.virtualenv: ignoring comment')
        else:
            tmp.append(line)
    new_text = "\n".join(tmp)
    tmp = None # free the list

    try:
        f = open(script_name)
        cur_text = f.read()
        f.close()
    except:
        cur_text = ''

    sys.stdout.write('Updating %s\n' % script_name)
    if cur_text == new_text:
        sys.stdout.write('  ... no changes (old file identical to new file).\n')
    else:
        sys.stdout.write('  ... changes detected; regenerating script.\n')
        f = open(script_name, 'w')
        f.write(new_text)
        f.close()
        os.chmod(script_name, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)

def main():
    if len(sys.argv) != 3:
        sys.stdout.write("vpy_create <config-file> <name>\n")
        sys.stdout.write("vpy_create vpy <name>\n")
        sys.exit(1)

    config_name = sys.argv[1]
    script_name = sys.argv[2]
    vpy_create(config_name, script_name)

if __name__ == '__main__':
    main()
