#!/usr/bin/env python2.7

import os
import sys
import subprocess


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(os.path.abspath(os.path.dirname(__file__)))
venv = '.batou'
venv = os.path.join(base, venv)
os.chdir(base)

if not os.path.exists(venv):
    print('Preparing virtualenv in %s...' % venv)
    cmd('virtualenv --setuptools --python=python2.7 %s' % venv)

cmd('%s/bin/pip install "pip>=1.2"' % venv)

try:
    cmd('%s/bin/python -c \'import gocept.package\'' % venv, quiet=True)
except Exception, e:
    missing = True
else:
    missing = False

if missing:
    print('Installing Sphinx - this can take a while...')
    cmd('%s/bin/pip install --egg -r %s/doc/doc-requirements' % (venv, base))

os.execv('%s/bin/doc' % venv, sys.argv)
