#! /usr/bin/env python

import os
import os.path
from optparse import OptionParser
import sys
import re
import glob
import shutil

vpykit_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

cwd = os.getcwd()

def call(cmd_):
    def _call(cmd_):
        popen = subprocess.Popen(cmd_, stdout=OUTPUT, stderr=subprocess.STDOUT)
        popen.communicate()[0]
        return popen.returncode
    
    cmd = cmd_[:]
    # We now assume that the caller will generate strings that are valid
    # within the context of the current interpreter.
    #str = str.replace('\\',os.sep)
    #str = str.replace('/',os.sep)
    if cmd[0].startswith('.'):
        cmd[0] = os.path.join(cwd, cmd[0])
    currdir = os.getcwd()
    OUTPUT.write("Running command '%s' in directory '%s'\n" %
                 (' '.join(cmd), currdir, ))
    OUTPUT.flush()
    try:
        import subprocess
        try:
            return _call(cmd)
        except OSError:
            cmd[0] = cmd[0] + ".exe"
            return _call(cmd)
    except ImportError:
        if os.path.exists(cmd[0]+".exe"):
            cmd[0] = cmd[0] + ".exe"
        ans = os.system(" ".join(cmd))
        return ans

parser=OptionParser()
parser.add_option('-c',
    help='Specify a configuration file',
    action='store',
    dest='config',
    default=None)
parser.add_option('-z',
    help='Specify a ZIP file',
    action='store',
    dest='zip',
    default=None)
parser.add_option("--trunk",
    help="Specify a trunk installation",
    action="store_true",
    dest="trunk",
    default=False)
parser.add_option("--site-packages",
    help="Install using Python site packages",
    action="store_true",
    dest="site",
    default=False)
parser.add_option('-p',
    help='Specify a package directory that is installed',
    action='append',
    dest='packages',
    default=[])
parser.add_option("--src",
    help="Specify the root source directory ",
    action="store",
    dest="srcdir",
    default='.')
parser.add_option("--build",
    help="Specify the root build directory ",
    action="store",
    dest="builddir",
    default='.')
parser.add_option("--logfile",
    help="Specify the logfile",
    action="store",
    dest="logfile",
    default=None)
(options,args) = parser.parse_args()

if options.logfile:
    OUTPUT=open(options.logfile,'w')
else:
    OUTPUT=sys.stdout
install_dir = os.path.join(options.builddir, 'python')
if os.path.exists(install_dir):
    sys.stdout.write('Python has already been installed at %s\n' %
                     (install_dir,))
    sys.exit(0)
else:
    sys.stdout.write('Installing Python at %s ...' %
                     (install_dir,))
    sys.stdout.flush()

#cmd = '%s%s/pyutilib.virtualenv/scripts/vpy_install %s --debug --trunk --config %s/default.ini' % (options.python and options.python+" " or "", vpykit_dir, site_packages, vpykit_dir)
cmd = [ sys.executable,
        os.path.join(vpykit_dir, 'pyutilib.virtualenv','scripts','vpy_install'),
        '--debug','--trunk',
        '--config', os.path.join(vpykit_dir,'default.ini') ]
if options.site:
    cmd.append('--system-site-packages')
else:
    cmd.append('--no-site-packages')
if options.config:
    cmd.extend(['--config', options.config])
if options.zip:
    cmd.extend(['--offline','--zip', options.zip])
cmd.append(install_dir)

rc = call(cmd)
OUTPUT.write("\n")
OUTPUT.flush()

virtual_python = os.path.join(install_dir, 'bin', 'python')
if rc == 0:
    for package in options.packages:
        dirname = package % options.srcdir
        for dir in glob.glob(dirname):
            cwd = os.getcwd()
            os.chdir(dir)
            OUTPUT.write('\nInstalling package at %s\n' % (dir,))
            rc = call([virtual_python, 'setup.py', 'develop'])
            OUTPUT.write("\n")
            OUTPUT.flush()
            #call(['rm','-Rf','build'])
            if os.path.exists('build'):
                shutil.rmtree('build')
            os.chdir(cwd)
            if rc != 0:
                break

if options.logfile:
    OUTPUT.close()
sys.stdout.write('done.\n')
if rc != 0:
    sys.stderr.write('ERROR: Problem installing Python.\n')
sys.stdout.write('See logfile: %s\n' % (options.logfile,))
sys.exit(rc)
