#!/usr/bin/env bash

# This script serves as the Django injection build step of the
# [**Python Buildpack**](https://github.com/heroku/heroku-buildpack-python)
# compiler.
#
# A [buildpack](http://devcenter.heroku.com/articles/buildpacks) is an
# adapter between a Python application and Heroku's runtime.
#
# This script is invoked by [`bin/compile`](/).

# ## Sanity Checks
#

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

echo "-----> Injecting legacy Django settings..."
echo " !     WARNING: Settings injection will be fully deprecated on January 1, 2013. More info:"
echo " !     https://devcenter.heroku.com/articles/django-injection "


echo "-----> Installing dj-database-url..."
pip install --use-mirrors 'dj-database-url>=0.2.0' | indent

SETTINGS_FILE=$(find . -maxdepth 2 -type f -name '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 dj_database_url

if 'DATABASES' not in locals():
    DATABASES = {}

if not 'default' in DATABASES:
    DATABASES['default'] = {}

DATABASES['default'].update(dj_database_url.config(default='postgres://'))

EOF

