#!/usr/bin/env python2.7
#
# This file is managed by batou. Don't edit directly. Use the './batou update'
# command to adjust versions.
#
# 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 = '{version}'
develop = '{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 --ignore-installed '
            '--no-deps -e {{}}'.format(develop))
    else:
        print('Pre-installing batou - this can take a while...')
        cmd('.batou/bin/pip install --ignore-installed '
            '--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)
