#!/bin/sh

# prerequisite : redis local server 

cd source

export DJANGO_SUPERUSER_PASSWORD=dev
#export CAVALIBA_AUTH_MODE=forced
export CAVALIBA_CELERY_BROKER_URL="redis://127.0.0.1:6379"
export CAVALIBA_CELERY_RESULT_BACKEND="redis://127.0.0.1:6379"
export CAVALIBA_FILES="./files/"
#export CAVALIBA_TASK_CELERY=sync
export CAVALIBA_DEBUG_AAA="no"


# BLOCK: task  => run task only
#if [ "$1" = "task" ]; then
#    uv run celery --workdir ./ -A core worker -B -s /tmp/celery --loglevel=info --concurrency 1
#    exit
#fi


# BLOCK: app
if [ -z "$1" ]; then

    # Collect static files
    uv run  manage.py check
    echo

    # not needed in DEV mode
    # echo "Collect static files"
    # uv run manage.py collectstatic --clear --noinput
    # echo


    echo "database migrations..."
    uv run manage.py migrate
    echo

    echo "cache tables..."
    uv run manage.py createcachetable
    echo

    echo "translations..."
    uv run manage.py compilemessages -v 0
    # verbose 0 is silent
    echo

    # not needed in DEV mode with auth forced
    echo "admin superuser if absent..."
    uv run manage.py createsuperuser --no-input --username admin --email dev@dev.nodev
    echo

    uv run manage.py cavaliba start
    echo

    echo "local TASK celery server"
    uv run celery --workdir ./ -A core worker -B -s /tmp/celery --loglevel=info --concurrency 1 &


    echo "local APP server"
    uv run python manage.py runserver 0.0.0.0:8000
    #uv run python manage.py runserver 127.0.0.1:8000
    #gunicorn core.wsgi:application --bind 0.0.0.0:8000 --log-level info --workers 4 --max-requests 500 --access-logfile '-' --error-logfile '-' --graceful-timeout 2
    # uv run gunicorn core.wsgi:application --bind 0.0.0.0:8000 

fi

# HELP
#if [ "$1" = "help" ]; then
echo "./start_dev.sh help  :  this help"
echo "./start_dev.sh       :  start local app + task in dev mode"
#echo "./start_dev.sh task :  start local celery in dev mode ; running local redis needed"
exit
#fi

