#!/bin/bash

in_serve="${1}"  # either django or gunicorn

serve="gunicorn"
if [ $# -gt 0 ]; then
    if [ "${in_serve}" != "django" ] && [ "${in_serve}" != "gunicorn" ]; then
        echo "Unknown option ${in_serve}. Fall back to gunicorn option"
    else
        serve="${in_serve}"
        echo "Using ${in_serve}"
    fi
fi

run_django_serve() {
    echo "Starting Django dev server"
    python3 manage.py runserver 0.0.0.0:8000 2>&1 >> /var/log/django_server.log
}

run_gunicorn_serve() {
    echo "Starting Gnuicorn server"
    gunicorn console.wsgi:application --bind 0.0.0.0:8000 --workers=3 --timeout 300 --access-logfile /var/log/gunicorn.acesss.log --error-logfile /var/log/gunicorn.error.log --log-file /var/log/gunicorn.log --access-logformat '%(h)s %(l)s %(t)s %(r)s %(q)s %(s)s %(B)s'
}

run_cmd_serve=run_gunicorn_serve
if [ "${serve}" == "django" ]; then
    run_cmd_serve=run_django_serve
fi

# pip3 install -r requirements.txt
# python3 manage.py makemessages --locale=en_US &&
# python3 manage.py makemessages --locale=ru_RU &&
# python3 manage.py compilemessages --locale=en_US && ## remove
# python3 manage.py compilemessages --locale=ru_RU && ## remove
python3 manage.py collectstatic --noinput && 
python3 manage.py makemigrations --noinput &&
python3 manage.py migrate --noinput &&
python3 manage.py load_rules &&
#find . -name "fixtures" -type d -exec bash -c 'for item in $(ls {}); do echo "Apply {}/$item fixture"; python3 manage.py loaddata $item; done' \; &&
$run_cmd_serve
