#!/bin/sh
set -e

echo "Starting Laravel entrypoint (Unified)..."

# Step 0: Wait for DB if configured
if [ -n "${DB_HOST:-}" ]; then
  echo "Waiting for DB at ${DB_HOST}:${DB_PORT:-5432}..."
  # Wait up to ~60s (60 * 1s)
  i=0
  while ! nc -z "$DB_HOST" "${DB_PORT:-5432}"; do
    i=$((i + 1))
    if [ "$i" -ge 60 ]; then
      echo "DB not reachable after 60s. Continuing anyway."
      break
    fi
    sleep 1
  done
  echo "DB check finished."
fi

# Step 1: Initialize persistent storage if needed
if [ ! "$(ls -A /var/www/storage 2>/dev/null)" ]; then
  echo "Initializing /var/www/storage..."
  cp -R /var/www/storage-init/. /var/www/storage
  chown -R www-data:www-data /var/www/storage
else
  echo "/var/www/storage already initialized."
fi

rm -rf /var/www/storage-init

# Step 2: Ensure environment is ready
if [ ! -f .env ]; then
  echo ".env file is missing!"
  echo "Provide it at runtime (bind mount, env_file, or secret) to /var/www/.env."
  exit 1
fi

# Ensure bootstrap/cache directory exists and writable BEFORE artisan
if [ ! -d bootstrap/cache ]; then
  echo "Creating bootstrap/cache directory..."
  mkdir -p bootstrap/cache
fi
chown -R www-data:www-data bootstrap/cache

# Step 3: Laravel setup and optimization
php artisan storage:link || true
php artisan config:clear
php artisan config:cache
php artisan route:cache
php artisan event:cache
php artisan package:discover --ansi

# Step 4: Set permissions
chown -R www-data:www-data /var/www/storage
chown -R www-data:www-data /var/www/bootstrap/cache

# Step 5: Ensure Laravel log directory exists
mkdir -p /var/www/storage/logs
chown -R www-data:www-data /var/www/storage/logs

# Step 6: Create supervisor log directories
mkdir -p /var/log/supervisor
chown -R root:root /var/log/supervisor

echo "Laravel setup complete. Starting Supervisor..."
exec supervisord -c /etc/supervisor/supervisord.conf

