#!/bin/sh

# start a non-docker cavaliba dev server with auto-reload

cd source

# prerequisite : redis local server  ; native or docker
# systemctl start redis
docker run --rm  --name redis -p 6379:6379 redis &


# conf
export CAVALIBA_ADMIN_PASSWORD=dev
export CAVALIBA_APIKEY_SECRET=devsecret
#export CAVALIBA_AUTH_MODE=forced
export CAVALIBA_FILES="./files/"
export CAVALIBA_DEBUG=1
export CAVALIBA_DEBUG_AAA="no"

# sync (main process / no celery started) | async
export CAVALIBA_TASK_CELERY=async
export CAVALIBA_CELERY_BROKER_URL="redis://127.0.0.1:6379"
export CAVALIBA_CELERY_RESULT_BACKEND="redis://127.0.0.1:6379"
export CAVALIBA_CACHE_DEFAULT_URL="redis://127.0.0.1:6379"
export CAVALIBA_CACHE_SESSION_URL="redis://127.0.0.1:6379"


# check
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

if [ "$CAVALIBA_TASK_CELERY" = "sync" ]; then
    echo "CAVALIBA_TASK_CELERY=sync : skipping celery worker, tasks run in the main process"
else
    echo "local TASK celery server"
    uv run celery --workdir ./ -A core worker -B -s /tmp/celery --loglevel=info --concurrency 2 &
fi


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
#uv run gunicorn core.wsgi:application --bind 0.0.0.0: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




