#!/bin/bash
# Container Startup Logger
# Logs container lifecycle events for debugging restarts

set -e

echo "=========================================="
echo "[CONTAINER-STARTUP] $(date '+%Y-%m-%d %H:%M:%S')"
echo "Container: igny8_backend"
echo "Hostname: $(hostname)"
echo "PID: $$"
echo "=========================================="

# Log environment info
echo "[INFO] Python version: $(python --version 2>&1)"
echo "[INFO] Django settings: ${DJANGO_SETTINGS_MODULE:-igny8_core.settings}"
echo "[INFO] Debug mode: ${DEBUG:-False}"
echo "[INFO] Database host: ${DB_HOST:-not set}"

# Check if this is a restart (look for previous process artifacts)
if [ -f /tmp/container_pid ]; then
    PREV_PID=$(cat /tmp/container_pid)
    echo "[WARNING] Previous container PID found: $PREV_PID"
    echo "[WARNING] This appears to be a RESTART event"
    echo "[WARNING] Check Docker logs for SIGTERM/SIGKILL signals"
else
    echo "[INFO] First startup (no previous PID file found)"
fi

# Save current PID
echo $$ > /tmp/container_pid

# Run database migrations (will skip if up to date)
echo "[INFO] Running database migrations..."
python manage.py migrate --noinput || echo "[WARNING] Migration failed or skipped"

# Collect static files (skip if already done)
echo "[INFO] Collecting static files..."
python manage.py collectstatic --noinput || echo "[WARNING] Collectstatic failed or skipped"

echo "=========================================="
echo "[CONTAINER-STARTUP] Initialization complete"
echo "[CONTAINER-STARTUP] Starting Gunicorn..."
echo "=========================================="

# Execute the CMD passed to the script (Gunicorn command)
exec "$@"
