#!/bin/sh
set -e

cd /var/www/html

# Ensure Laravel's writable dirs exist (dev bind-mount may not have them yet).
mkdir -p \
    storage/framework/cache \
    storage/framework/sessions \
    storage/framework/views \
    storage/logs \
    bootstrap/cache

# When running as root (the `app` service / prod), hand storage to the app user
# so php-fpm (which runs as `app`) can write. Non-root services (vite/queue/
# reverb run as the host UID) skip this — they already own the bind-mount.
if [ "$(id -u)" = "0" ]; then
    chown -R app:app storage bootstrap/cache 2>/dev/null || true
fi

# Freeze the configured panel domain as the active one — ONLY in the web/app container
# (its CMD is supervisord). The queue/reverb workers share this entrypoint and, in dev,
# the same bind-mounted storage; snapshotting from a worker restart would apply a pending
# domain without an app restart, breaking the "applies on restart" boundary. Best-effort:
# a failure here must never block startup.
if [ "$1" = "supervisord" ]; then
    php artisan clusev:snapshot-domain >/dev/null 2>&1 || true
fi

exec "$@"
