#!/bin/bash

# set location to script directory
cd "${0%/*}"

if [ -z "$CI" ];
then
  # kill all subprocess on exit so that Bitbucket Pipelines process will not hang
  trap "exit" INT TERM ERR
  trap "kill 0" EXIT
else echo "CI is set to $CI";
fi

# script should fail when any process returns non zero code
set -ev

# handle arguments
SKIP_SETUP=false
START_BACKGROUND=false

for i in "$@"
do
case $i in
    --start-background)
    START_BACKGROUND=true
    shift # past argument
    ;;
    --skip-setup)
    SKIP_SETUP=true
    shift # past argument with no value
    ;;
    *)
          # unknown option
    ;;
esac
done

echo "SKIP_SETUP = ${SKIP_SETUP}"

POSTGRES_DB=${POSTGRES_DB:-vbv_lernwelt}
POSTGRES_HOST=${POSTGRES_HOST:-localhost}
POSTGRES_PORT=${POSTGRES_PORT:-5432}
POSTGRES_USER=${POSTGRES_USER:-postgres}
DJANGO_PORT=${DJANGO_PORT:-8000}

mypsql() {
  psql -h "${POSTGRES_HOST}" -p "${POSTGRES_PORT}" -U "${POSTGRES_USER}" "$@"
}

if [ "$SKIP_SETUP" = false ]; then
    # TODO: in heroku we must do a `pg:resets` to reset the db
    echo "Check postgres connection"
    mypsql -c "SELECT 1"
    echo "Drop all connections to $POSTGRES_DB"
    mypsql -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$POSTGRES_DB' AND pid <> pg_backend_pid();" > /dev/null 2>&1
    echo "Drop database: $POSTGRES_DB"
    mypsql -c "drop database if exists $POSTGRES_DB;"
    echo "Create database: $POSTGRES_DB"
    mypsql -c "create database $POSTGRES_DB;"

    echo "initialize database for django"
    python3 server/manage.py createcachetable --settings="$DJANGO_SETTINGS_MODULE"
    python3 server/manage.py migrate --settings="$DJANGO_SETTINGS_MODULE"
    python3 server/manage.py create_default_users --settings="$DJANGO_SETTINGS_MODULE"
    python3 server/manage.py create_default_learning_path --settings="$DJANGO_SETTINGS_MODULE"

    # make django translations
    (cd server && python3 manage.py compilemessages --settings="$DJANGO_SETTINGS_MODULE")
else
    # TODO: can we reset important data without resetting the database?
    echo "Skip database setup"
    # python3 src/manage.py cypress_reset --settings="$DJANGO_SETTINGS_MODULE"
fi

if [ "$START_BACKGROUND" = true ]; then
    python3 server/manage.py runserver "${DJANGO_PORT}" --settings="$DJANGO_SETTINGS_MODULE" > /dev/null &
else
    python3 server/manage.py runserver "${DJANGO_PORT}" --settings="$DJANGO_SETTINGS_MODULE"
fi
