#!/bin/sh
set -e

echo "[entrypoint] Starting Laravel application setup..."

# Redirect PHP errors to stderr so they appear in Railway logs
cat > /usr/local/etc/php/conf.d/docker-php-logging.ini <<'EOF'
log_errors = On
error_log = /dev/stderr
display_errors = Off
error_reporting = E_ALL
EOF

# Ensure the Laravel log file exists and is writable, then tail it to stdout
# so Laravel application logs appear in Railway's log stream
mkdir -p /var/www/html/storage/logs
touch /var/www/html/storage/logs/laravel.log
chown www-data:www-data /var/www/html/storage/logs/laravel.log

# Stream Laravel log to stdout in the background
tail -F /var/www/html/storage/logs/laravel.log &

# Run Laravel bootstrap tasks; log any failures but don't abort startup
echo "[entrypoint] Running artisan config:cache..."
php /var/www/html/artisan config:cache 2>&1 || echo "[entrypoint] WARNING: config:cache failed — check your .env and config files"

echo "[entrypoint] Running artisan route:cache..."
php /var/www/html/artisan route:cache  2>&1 || echo "[entrypoint] WARNING: route:cache failed"

echo "[entrypoint] Running artisan view:cache..."
php /var/www/html/artisan view:cache   2>&1 || echo "[entrypoint] WARNING: view:cache failed"

echo "[entrypoint] Bootstrap complete. Handing off to supervisord..."

# Hand off to supervisord, which manages PHP-FPM and Nginx in the foreground
exec /usr/bin/supervisord -n -c /etc/supervisor/conf.d/supervisord.conf
