#!/usr/bin/env python
#
# This file is managed by batou. Don't edit directly. Use the './batou update'
# command to adjust versions.
#
# This needs to be able to run with a lot of Python versions
# I'd like to support this for Python 3.3, 3.2, 2.7, 2.6, and 2.5
# XXX Gotta test that fact.
# Also, this file is intended to be as small as possible getting batou working
# somehow and then use that code to continue.

import os
import sys
import subprocess

version = ''
develop = '../..'


def cmd(c, quiet=False):
    try:
        subprocess.check_output([c], stderr=subprocess.PIPE, shell=True)
    except subprocess.CalledProcessError, e:
        if not quiet:
            print("{} returned with exit code {}".format(c, e.returncode))
            print(e.output)
        raise

base = os.path.dirname(__file__)
os.chdir(base)

# Do we have a virtualenv?
if not os.path.exists(base + '/.batou'):
    print('Preparing virtualenv in .batou ...')
    # Discover the right venv cmd. Or let batou figure that out later in a second phase?
    cmd('virtualenv --python=python2.7 .batou')

cmd('.batou/bin/pip install "pip>=1.2"')

try:
    cmd('.batou/bin/python -c \'import batou.bootstrap\'', quiet=True)
except Exception, e:
    missing = True
else:
    missing = False

if missing or develop:
    if develop:
        if missing:
            print('Pre-installing batou - this can take a while...')
        cmd('.batou/bin/pip install --no-deps -e {}'.format(develop))
    else:
        print('Pre-installing batou - this can take a while...')
        cmd('.batou/bin/pip install --no-deps --egg batou=={}'.format(version))


os.environ['BATOU_VERSION'] = version
os.environ['BATOU_DEVELOP'] = develop

# Pass control over the bare-bone batou's bootstrapping code. Good luck!
os.execv('.batou/bin/python', ['.batou/bin/python', '-c', 'import batou.bootstrap; batou.bootstrap.bootstrap()'] + sys.argv)
