#!/bin/sh
# Production entrypoint for the PHP-FPM container.
# Runs as root so it can fix volume permissions, then drops to the app user.
set -e

# The storage/app/public volume is created root-owned by Docker on first run;
# make it writable by the app user (and shareable with the web container).
chown -R app:app storage bootstrap/cache 2>/dev/null || true

# Wait for the database to accept connections before migrating.
echo "Waiting for the database..."
until su-exec app php -r '
    try {
        new PDO(
            sprintf("mysql:host=%s;port=%s", getenv("DB_HOST") ?: "mysql", getenv("DB_PORT") ?: "3306"),
            getenv("DB_USERNAME") ?: "root",
            getenv("DB_PASSWORD") ?: ""
        );
        exit(0);
    } catch (Throwable $e) {
        exit(1);
    }
' 2>/dev/null; do
    sleep 2
done

# Apply schema changes and (re)build the production caches from the current env.
su-exec app php artisan migrate --force
su-exec app php artisan optimize

# Run php-fpm with the master as root (so it can open its error log on the
# container's stderr) and let it fork the worker processes as the app user.
# Dropping privileges with su-exec instead leaves stderr owned by root, so the
# app user cannot reopen /proc/self/fd/2 and FPM fails to start.
cat > /usr/local/etc/php-fpm.d/zzz-prod.conf <<'EOF'
[www]
user = app
group = app
EOF

exec "$@"
