#!/bin/bash

: ${UWSGI_BUFFER_SIZE:=32768}
: ${UWSGI_NAME:=uwsgi}
: ${UWSGI_SOCKET_NAME:=${UWSGI_NAME}.sock}
: ${UWSGI_LOG_NAME:=${UWSGI_NAME}.log}
: ${UWSGI_LOG:=/data/run/${UWSGI_LOG_NAME}}
: ${UWSGI_SOCKET:=/data/run/${UWSGI_SOCKET_NAME}}
: ${UWSGI_PIDFILE_NAME:=uwsgi.pid}
: ${UWSGI_PIDFILE:=/data/run/${UWSGI_SOCKET_NAME}}
: ${UWSGI_PROCESSES:=4}
: ${HTTP_PORT:=8000}
: ${HTTP_ADDRESS:=0.0.0.0}
: ${HTTP_SOCKET:=${HTTP_ADDRESS}:${HTTP_PORT}}
: ${UWSGI_MAX_REQUESTS:=4000}

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

collectstatic() {
    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
}

createsuperuser() {
    poetry run python manage.py createsuperuser "$@"
}

if [ $# -eq 0 -o "$1" = "start" ]; then
    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 "$HTTP_SOCKET" \
            --socket "$UWSGI_SOCKET" \
            --processes $UWSGI_PROCESSES \
            --harakiri 60 \
            --max-requests $UWSGI_MAX_REQUESTS \
            --buffer-size $UWSGI_BUFFER_SIZE \
            --vacuum \
            --venv "$venv" \
            --home "$venv" \
            --logto "$UWSGI_LOG"
        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 $HTTP_SOCKET
        rc=$?
        if [ $rc -ne 0 ]; then
            echo "Developemnt server was not started!" >&2
            exit $rc
        fi
    fi
elif [ "$1" == "init" -o "$1" == "update" ]; then
    migrate_db
    collectstatic
elif [ "$1" == "suinit" ]; then
    shift
    migrate_db
    collectstatic
    createsuperuser "$@"
elif [ "$1" == "migrate" ]; then
    migrate_db
elif [ "$1" == "collectstatic" ]; then
    collectstatic
elif [ "$1" == "createsuperuser" ]; then
    shift
    createsuperuser "$@"
else
    exec "$@"
fi
