#!/bin/sh
set -e

# Lightweight wait-for-postgres using nc (expects DATABASE_HOST and DATABASE_PORT env vars)
if [ -n "${DATABASE_HOST}" ]; then
  host="$DATABASE_HOST"
  port="${DATABASE_PORT:-5432}"
  echo "Waiting for database at ${host}:${port}..."
  while ! nc -z "$host" "$port"; do
    sleep 1
  done
fi

echo "Applying database migrations..."
python manage.py migrate --noinput

echo "Collecting static files..."
python manage.py collectstatic --noinput

if [ "${SERVER_TYPE}" = "daphne" ] || [ "${SERVER_TYPE}" = "asgi" ]; then
  echo "Starting daphne..."
  exec daphne -b 0.0.0.0 -p 8000 rad.asgi:application
else
  echo "Starting gunicorn..."
  exec gunicorn rad.wsgi:application \
      --name rad_gunicorn \
      --bind 0.0.0.0:8000 \
      --workers ${GUNICORN_WORKERS:-3} \
      --log-level ${GUNICORN_LOGLEVEL:-info}
fi
