#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Startup script for the Django project
# -----------------------------------------------------------------------------
# This script ensures that the development environment is ready to run.
#
# Features:
#   - Runs database migrations
#   - Creates a superuser if it does not already exist
#   - Starts the Django development server
#
# Note:
#   This script is for local development only.
#   In production you should use a proper WSGI/ASGI server (e.g., Gunicorn, Daphne).
# -----------------------------------------------------------------------------

set -e  # Exit immediately if a command exits with a non-zero status

# Load environment variables from .env if available
if [ -f ".env" ]; then
  export $(grep -v '^#' .env | xargs)
fi

# Ensure we are in the project root directory
cd "$(dirname "$0")"

echo ">>> Running migrations..."
python manage.py migrate --noinput

echo ">>> Checking if superuser exists..."
python manage.py shell <<EOF
from django.contrib.auth import get_user_model
User = get_user_model()
username = "${DJANGO_SUPERUSER_USERNAME:-admin}"
if not User.objects.filter(username=username).exists():
    print(f"Creating superuser '{username}'...")
    User.objects.create_superuser(
        username=username,
        email="${DJANGO_SUPERUSER_EMAIL:-admin@example.com}",
        password="${DJANGO_SUPERUSER_PASSWORD:-changeme}"
    )
else:
    print(f"Superuser '{username}' already exists.")
EOF

echo ">>> Starting Django development server at http://127.0.0.1:8000 ..."
python manage.py runserver 0.0.0.0:8000