#!/bin/sh
set -e

echo "============================================="
echo " Ujian Online - Starting Application"
echo "============================================="

# --- Set default PM_MAX_CHILDREN if not provided ---
export PM_MAX_CHILDREN=${PM_MAX_CHILDREN:-20}

echo "[INFO] PM_MAX_CHILDREN = $PM_MAX_CHILDREN"
echo "[INFO] REDIS_HOST = ${REDIS_HOST:-127.0.0.1}"
echo "[INFO] CACHE_STORE = ${CACHE_STORE:-redis}"
echo "[INFO] SESSION_DRIVER = ${SESSION_DRIVER:-redis}"
echo "[INFO] QUEUE_CONNECTION = ${QUEUE_CONNECTION:-redis}"

# --- Ensure storage directories exist ---
mkdir -p /var/www/html/storage/framework/{cache,sessions,views,testing}
mkdir -p /var/www/html/storage/logs
mkdir -p /var/www/html/bootstrap/cache
mkdir -p /tmp/opcache

# --- Fix permissions ---
chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache

# --- Wait for database to be ready ---
echo "[INFO] Waiting for database..."
MAX_RETRIES=30
RETRY_COUNT=0
until php /var/www/html/artisan db:monitor --databases=mysql > /dev/null 2>&1 || [ $RETRY_COUNT -eq $MAX_RETRIES ]; do
    RETRY_COUNT=$((RETRY_COUNT + 1))
    echo "[INFO] Database not ready yet... retry $RETRY_COUNT/$MAX_RETRIES"
    sleep 2
done

if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
    echo "[WARN] Database might not be ready, continuing anyway..."
fi

# --- Run migrations (safe for production with --force) ---
echo "[INFO] Running migrations..."
php /var/www/html/artisan migrate --force --no-interaction 2>/dev/null || echo "[WARN] Migration failed or no pending migrations"

# --- Laravel production caching ---
echo "[INFO] Caching Laravel configurations..."
php /var/www/html/artisan config:cache
php /var/www/html/artisan route:cache
php /var/www/html/artisan view:cache
php /var/www/html/artisan event:cache

# --- Create storage link if not exists ---
php /var/www/html/artisan storage:link --force 2>/dev/null || true

echo "============================================="
echo " Application ready! Starting services..."
echo "============================================="

# --- Execute CMD (supervisord) ---
exec "$@"
