#!/bin/bash
# Production startup script (for systemd or manual)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DJANGO_DIR="$SCRIPT_DIR/nonpacks"
PYTHON_BIN="$SCRIPT_DIR/venv/bin/python"
GUNICORN_BIN="$SCRIPT_DIR/venv/bin/gunicorn"

FLAG_FILE="$SCRIPT_DIR/.migrations_done"
FORCE_SETUP=0

# Check for --force-setup argument
for arg in "$@"; do
    if [ "$arg" = "--force-setup" ]; then
        FORCE_SETUP=1
    fi
done

cd "$DJANGO_DIR"

# Run migrations once, flag it, skip next time
if [ ! -f "$FLAG_FILE" ] || [ $FORCE_SETUP -eq 1 ]; then
    echo "Running database migrations..."
    "$PYTHON_BIN" manage.py migrate
    touch "$FLAG_FILE"
    echo "Migrations applied. Flag file created: $FLAG_FILE"
else
    echo "Database already migrated (found $FLAG_FILE). Skipping."
    echo "To force re-run, use: $0 --force-setup"
fi

# Rebuild the vanilla entity-texture index (gitignored generated file)
echo "Rebuilding vanilla entity-texture index..."
"$PYTHON_BIN" manage.py refresh_vanilla_index

# Collect static files (served by gunicorn via whitenoise)
"$PYTHON_BIN" manage.py collectstatic --noinput

# Directory for gunicorn's access log (parsed by the stats page).
mkdir -p "$SCRIPT_DIR/logs"

echo "Starting Gunicorn on 0.0.0.0:8120..."
exec "$GUNICORN_BIN" \
    --workers 3 \
    --bind 0.0.0.0:8120 \
    --access-logfile "$SCRIPT_DIR/logs/gunicorn-access.log" \
    --access-logformat '%(h)s %(t)s "%(r)s" %(s)s %(b)s %(L)s' \
    common.wsgi:application
