#!/bin/sh
set -eu

cd /var/www/html

# Répertoires persistants (volumes) : recréés si absents.
mkdir -p \
    storage/framework/cache/data \
    storage/framework/sessions \
    storage/framework/views \
    storage/logs \
    storage/app/private \
    storage/app/public

chown -R www-data:www-data storage bootstrap/cache
chmod -R ug+rwX storage bootstrap/cache

if [ -z "${APP_KEY:-}" ]; then
    echo "ERREUR : APP_KEY n'est pas défini. Renseignez-le dans .env." >&2
fi

if [ "${AUTO_MIGRATE:-false}" = "true" ]; then
    echo "Attente de la base de données et exécution des migrations..."
    attempt=0
    until gosu www-data php artisan migrate --force --no-interaction; do
        attempt=$((attempt + 1))
        if [ "$attempt" -ge 30 ]; then
            echo "ERREUR : base de données indisponible après 30 tentatives." >&2
            exit 1
        fi
        sleep 2
    done
fi

if [ "${APP_ENV:-production}" = "production" ]; then
    gosu www-data php artisan config:cache --no-interaction >/dev/null 2>&1 || true
    gosu www-data php artisan view:cache --no-interaction >/dev/null 2>&1 || true
fi

# Les workers (scheduler, queue) tournent avec l'utilisateur web.
case "${1:-}" in
    php)
        exec gosu www-data "$@"
        ;;
    *)
        exec "$@"
        ;;
esac
