#!/usr/bin/env bash

set -Eeuo pipefail

# from https://stackoverflow.com/a/45977232
# Following regex is based on https://www.rfc-editor.org/rfc/rfc3986#appendix-B with
# additional sub-expressions to split authority into userinfo, host and port
#
readonly URI_REGEX='^(([^:/?#]+):)?(//((([^/?#]+)@)?([^:/?#]+)(:([0-9]+))?))?(/([^?#]*))(\?([^#]*))?(#(.*))?'
#                    ↑↑            ↑  ↑↑↑            ↑         ↑ ↑            ↑ ↑        ↑  ↑        ↑ ↑
#                    |2 scheme     |  ||6 userinfo   7 host    | 9 port       | 11 rpath |  13 query | 15 fragment
#                    1 scheme:     |  |5 userinfo@             8 :…           10 path    12 ?…       14 #…
#                                  |  4 authority
#                                  3 //…

parse_host () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[7]}"
}

parse_port () {
    [[ "$@" =~ $URI_REGEX ]] && echo "${BASH_REMATCH[9]}"
}

dbhost=$(parse_host "${DATABASE_URL}")
dbport=$(parse_port "${DATABASE_URL}")

cd ${BASEDIR}

if [[ "$*" =~ 'uwsgi' ]]; then
    echo "Waiting for postgres on ${dbhost}:${dbport}..."

    while ! nc -z ${dbhost} ${dbport}; do
        sleep 0.1
    done

    echo "PostgreSQL started"
    
    python manage.py syncdb --migrate
    python manage.py collectstatic --noinput --clear

fi

exec "$@"