#!/usr/bin/env bash
echo "-----> Injecting Django settings..."

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
import sys
import urlparse

# Register database schemes in URLs.
urlparse.uses_netloc.append('postgres')
urlparse.uses_netloc.append('mysql')

try:

    # Check to make sure DATABASES is set in settings.py file.
    # If not default to {}

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

    if 'DATABASE_URL' in os.environ:
        url = urlparse.urlparse(os.environ['DATABASE_URL'])

        # Ensure default database exists.
        DATABASES['default'] = DATABASES.get('default', {})

        # Update with environment configuration.
        DATABASES['default'].update({
            '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 Exception:
    print 'Unexpected error:', sys.exc_info()

EOF





# Collect static files.
set +e
echo "-----> Collecting static files"

OUT=$(python $PROJECT/manage.py collectstatic --noinput 2>&1)
[ $? -ne 0 ] && STATIC_FAILED=1

if [ "$STATIC_FAILED" ]; then
    echo " !     Error running manage.py collectstatic. See http://devcenter.heroku.com/articles/django-assets for more info."
else
    echo "$OUT" | indent
fi

set -e
