#!/bin/bash

echo "Migrating database ..."
poetry run python manage.py migrate
if [ $? -ne 0 ]; then
    echo "Unable to migrate database!" >&2
    exit 5
fi

echo "Running collectstatic ..." 
yes yes | poetry run python manage.py collectstatic
if [ $? -ne 0 ]; then
    echo "Unable to collect static files!" >&2
    exit 5
fi

if [ -z "$DEBUG" -o $DEBUG != "1" ]; then
    echo "Starting UWSGI server ..."
    venv="$(poetry env info | head -n 6 | grep Path | awk '{print $2}')"
    poetry run uwsgi \
        --chdir /app \
        --module django_project.wsgi:application \
        --master --pidfile /data/run/uwsgi.pid \
        --http-socket '0.0.0.0:8000' \
        --socket /data/run/uwsgi.sock \
        --processes 5 \
        --harakiri 60 \
        --max-requests 5000 \
        --vacuum \
        --venv "$venv" \
        --home "$venv"
        
    rc=$?
    if [ $rc -ne 0 ]; then
        echo "UWSGI Server not started" >&2
        exit $rc
    fi
else
    echo "Starting development server ..."
    poetry run python manage.py runserver 0.0.0.0:8000
    rc=$?
    if [ $rc -ne 0 ]; then
        echo "Developemnt server was not started!" >&2
        exit $rc
    fi
fi
