#!/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 -e

# handle arguments
SKIP_SETUP=false
START_BACKGROUND=false
courses=()

# Parse positional arguments
while [[ $# -gt 0 ]]
do
    key="$1"

    case $key in
        -f|--file)
            shift
            ;;
        --start-background)
            START_BACKGROUND=true
            shift
            ;;
        --skip-setup)
            SKIP_SETUP=true
            shift
            ;;
        --courses)
            shift # Shift past the option
            while [[ $# -gt 0 ]] && ! [[ $1 == "--"* ]]
            do
                courses+=("$1")
                shift # Shift past the value
            done
            ;;
        *)
            echo "Unknown option: $key"
            exit 1
            ;;
    esac
done

echo "SKIP_SETUP = ${SKIP_SETUP}"

# Prepend "-c" to each item in courses
for i in "${!courses[@]}"
do
    courses[$i]="-c ${courses[$i]}"
done

# Join the list with a space
IFS=' ' course_param="${courses[*]}"
echo "$course_param"

# migrate env vars to the built-in postgres variables
if [ -z ${PGDATABASE+x} ]; then # var is empty
    PGDATABASE=${POSTGRES_DB:-vbv_lernwelt};
fi
if [ -z ${PGHOST+x} ]; then # var is empty
    PGHOST=${POSTGRES_HOST:-localhost};
fi
if [ -z ${PGPORT+x} ]; then # var is empty
    PGPORT=${POSTGRES_PORT:-5432}
fi
if [ -z ${PGUSER+x} ]; then # var is empty
    PGUSER=${POSTGRES_USER:-postgres}
fi
DJANGO_PORT=${DJANGO_PORT:-8000}


if [ "$SKIP_SETUP" = false ]; then
    # TODO: in heroku we must do a `pg:resets` to reset the db
    echo "Check postgres connection"
    psql -d postgres -c "SELECT 1" # use default db to connect to
    echo "Drop all connections to $PGDATABASE"
    psql -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$PGDATABASE' AND pid <> pg_backend_pid();" > /dev/null 2>&1 || true
    echo "Drop database: $PGDATABASE"
    psql -d postgres -c "drop database if exists $PGDATABASE;" # use default db to drop another database, can't drop the currently connected database
    echo "Create database: $PGDATABASE"
    psql -d postgres -c "create database $PGDATABASE;" # use default database, as the set database does not exist currently

    echo "initialize database for django"
    python server/manage.py createcachetable
    python server/manage.py migrate
    python server/manage.py create_default_users
    echo "python server/manage.py create_default_courses $course_param"
    python server/manage.py create_default_courses $course_param
    python server/manage.py create_default_notifications

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

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