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

set -eo pipefail

BIN_DIR=$(cd $(dirname $0); pwd) # absolute path
ROOT_DIR=$(dirname $BIN_DIR)
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"
VENDORED_MEMCACHED="http://cl.ly/0a191R3K160t1w1P0N25/vendor-libmemcached.tar.gz"

indent() {
  RE="s/^/       /"
  [ $(uname) == "Darwin" ] && sed -l "$RE" || sed -u "$RE"
}

virtualenv() {
  python - "$@" <<EOF
import sys
sys.path.insert(0, "$ROOT_DIR/src/virtualenv-1.6.4")
import virtualenv
virtualenv.main()
EOF
}

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

# warn a checked-in virtualenv
if [ -d "lib" ] || [ -d "bin" ]; then
  echo " !     You have a virtualenv checked in. You should ignore the appropriate paths in your repo. See http://devcenter.heroku.com/articles/gitignore for more info.";
fi

# reject a conflicting checked-in virtualenv
if [ -f "lib/python2.7" ]; then
  echo " !     Checked-in virtualenv conflict."
  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 --distribute . | indent


# if pylibmc within requirements, use vendored libmemcached
if grep -Fxq "pylibmc" requirements.txt
then
    echo "-----> Noticed pylibmc. Bootstrapping libmemcached."
    curl -O $VENDORED_MEMCACHED
    tar -zxvf vendor-libmemcached.tar.gz
    ls
fi




# if Django, 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" | indent

  cat >>$SETTINGS_FILE <<EOF

import os, sys, urlparse
urlparse.uses_netloc.append('postgres')
urlparse.uses_netloc.append('mysql')
try:
    if os.environ.has_key('DATABASE_URL'):
        url = urlparse.urlparse(os.environ['DATABASE_URL'])
        DATABASES['default'] = {
            '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 | indent

set +e
OUT=$(virtualenv --relocatable .)
[ $? -ne 0 ] && {
  echo " !     Error making virtualenv relocatable"
  echo "$OUT" | indent
  exit 1
}
set -e

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