#!/bin/bash
set -e

source ./.env/bin/activate
export C3NAV_DATABASE=postgres://mindshub:test@localhost:5432/insignorocketdb
export C3NAV_DEBUG=True

if [[ $# == 1 ]] && [[ $1 == "stop" ]]; then
    echo "Just stopping the postgres container"
    sudo docker stop postgres
    sudo docker container rm -f postgres
    echo "Stopped the postgres container"
elif [[ $# == 1 ]] && [[ $1 == "db" ]]; then
    echo "Setting up database"
    sudo docker run -d --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=test -e POSTGRES_USER=mindshub postgres
    until psql "postgres://mindshub:test@localhost:5432" <<< "CREATE DATABASE insignorocketdb;"; do
        sleep 0.5;
    done;
    psql "postgres://mindshub:test@localhost:5432/insignorocketdb" < auth_user.sql
    psql "postgres://mindshub:test@localhost:5432/insignorocketdb" < dump.sql
    pushd src
    python manage.py migrate
    echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'admin')" | python manage.py shell
    popd
    echo "Successfully setup database"
elif [[ $# == 1 ]] && [[ $1 == "run" ]]; then
    echo "Processing updates and running server"
    pushd src
    python manage.py processupdates
    python manage.py runserver
    popd
elif [[ $# == 1 ]] && [[ $1 == "run_without_output" ]]; then
    echo "Processing updates and running server without output"
    pushd src 2>&1 > /dev/null
    python manage.py processupdates 2>&1 | (grep -e "^ERROR" -e "^WARNING" -e "^HTTP" || true)
    python manage.py runserver 2>&1 | (grep -e "^ERROR" -e "^WARNING" -e "^HTTP" || true)
    popd 2>&1 > /dev/null
elif [[ $# > 0 ]] && [[ $1 == "manage" ]]; then
    pushd src
    python manage.py "${@:2}"
    popd
else
    echo "Usage: $0 [stop|db|run|run_without_output|manage]"
fi
