#!/usr/bin/env bash
# bin/compile <build-dir> <cache-dir>

set -eo pipefail

BIN_DIR=$(cd $(dirname $0); pwd) # absolute path
BUILD_DIR=$1
CACHE_DIR=$2

NAME=$($BIN_DIR/detect $BUILD_DIR)
PIP_DOWNLOAD_CACHE=${PIP_DOWNLOAD_CACHE:-$CACHE_DIR/pip_downloads}
VIRTUALENV_DIRS="bin include lib"

function sed() {
  # prefer GNU sed over BSD sed on OS X
  $(which gsed || which sed) "$@"
}

cd $BUILD_DIR

# reject a non-packaged Django app
if [ "$NAME" = "Python" ]; then
  [ -f manage.py ] && [ -f settings.py ] && { echo " !     Django app must be in a package subdirectory"; exit 1; }
fi

# copy artifacts out of cache if exists
mkdir -p $CACHE_DIR
for dir in $VIRTUALENV_DIRS; do
  cp -R $CACHE_DIR/$dir . &> /dev/null || true
done

echo "-----> Preparing virtualenv version $(virtualenv --version)"
virtualenv --no-site-packages . | sed -u 's/^/       /'

#echo "-----> Byte-compiling code"
find . -name "*.py" | grep -v bin/manage.py | xargs bin/python -m py_compile

# if Django, inject psycopg and append settings
if [ "$NAME" = "Python/Django" ]; then
  echo "-----> Django settings injection"

  SETTINGS_FILE=$(ls **/settings.py | head -1)
  PROJECT=$(dirname $SETTINGS_FILE)
  echo "       Injecting code into $SETTINGS_FILE to read from DATABASE_URL"
  
  cat >>$SETTINGS_FILE <<EOF
import os, urlparse
try:
    if os.environ.has_key('DATABASE_URL'):
        urlparse.uses_netloc.append('postgres')
        urlparse.uses_netloc.append('mysql')
        url = urlparse.urlparse(os.environ['DATABASE_URL'])
        DATABASES['default'] = {
            'ENGINE':   'django.db.backends.postgresql_psycopg2',
            'NAME':     url.path[1:],
            'USER':     url.username,
            'PASSWORD': url.password,
            'HOST':     url.hostname,
            'PORT':     url.port,
        }
        if url.scheme == 'postgres':
            DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql_psycopg2'
        if url.scheme == 'mysql':
            DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
except:
    print "Unexpected error:", sys.exc_info()

EOF
fi

echo "-----> Installing dependencies using pip version $(bin/pip --version | awk '{print $2}')"
PIP_DOWNLOAD_CACHE=$PIP_DOWNLOAD_CACHE bin/pip install --use-mirrors -r requirements.txt | sed -u 's/^/       /'

OUT=$(virtualenv --relocatable .)
[ $? -ne 0 ] && {
  echo " !     Error making virtualenv relocatable"
  echo "$OUT" | sed -u 's/^/       /'
  exit 1
}

# store new artifacts in cache
for dir in $VIRTUALENV_DIRS; do
  rm -rf $CACHE_DIR/$dir
  cp -R $dir $CACHE_DIR/
done
