#!/usr/bin/env bash

source $BIN_DIR/utils

MANAGE_FILE=$(find . -maxdepth 3 -type f -name 'manage.py' -printf '%d\t%P\n' | sort -nk1 | cut -f2 | head -1)
MANAGE_FILE=${MANAGE_FILE:-fakepath}

[ -f .heroku/collectstatic_disabled ] && DISABLE_COLLECTSTATIC=1
pip-grep -s requirements.txt django Django && DJANGO_INSTALLED=1

bpwatch start collectstatic

if [ ! "$DISABLE_COLLECTSTATIC" ] && [ -f "$MANAGE_FILE" ] && [ "$DJANGO_INSTALLED" ]; then
    set +e

    echo "-----> Preparing static assets with 'collectstatic'."

    echo "       Running collectstatic..."
    python $MANAGE_FILE collectstatic --noinput  2>&1 | sed '/^Copying/d;/^$/d;/^ /d' | indent

    # Display a warning if collectstatic failed.
    [ $? -ne 0 ] && {
        echo " !     Error while runnning '$ python $MANAGE_FILE collectstatic --noinput'."
        echo "       See traceback above for more details."
        echo "       More info: http://devcenter.heroku.com/articles/django-assets"
        exit 1
    }

    set -e
    echo
fi

bpwatch stop collectstatic
