#!/usr/bin/env bash
set -euo pipefail
cd /var/www/html

ensure_composer_dependencies() {
    if php -r "if (!file_exists('vendor/autoload.php')) { exit(1); } require 'vendor/autoload.php'; exit((class_exists('Dompdf\\Options') && class_exists('PhpOffice\\PhpSpreadsheet\\Spreadsheet') && class_exists('XLSXWriter')) ? 0 : 1);"; then
        echo "[entrypoint] Composer dependencies OK"
        return
    fi

    echo "[entrypoint] Missing or stale vendor dependencies -> running composer install"
    composer install --no-interaction --prefer-dist --optimize-autoloader
}

# Fast path: skip all bootstrap if SKIP_BOOTSTRAP=1
if [ "${SKIP_BOOTSTRAP:-0}" = "1" ]; then
    ensure_composer_dependencies
    sed -i 's/^listen = .*/listen = 0.0.0.0:9000/' /usr/local/etc/php-fpm.d/www.conf
    echo "[entrypoint] SKIP_BOOTSTRAP=1 -> skipping npm/migrations/cache warmup"
    touch /tmp/bootstrapped
    echo "[entrypoint] Starting PHP-FPM (skip path)"
    exec php-fpm
fi

# Fast path: if this container already bootstrapped, just start FPM
if [ -f /tmp/bootstrapped ]; then
    ensure_composer_dependencies
    sed -i 's/^listen = .*/listen = 0.0.0.0:9000/' /usr/local/etc/php-fpm.d/www.conf
    echo "[entrypoint] Starting PHP-FPM (fast path)"
    exec php-fpm
fi

echo "[entrypoint] Waiting for Database connection..."
if [ -n "${DB_HOST:-}" ] && [ -n "${DB_PORT:-}" ]; then
    for i in {1..60}; do
        if nc -z "$DB_HOST" "$DB_PORT"; then
            echo "[entrypoint] Database is ready!"
            break
        fi
        echo "[entrypoint] Waiting for DB at $DB_HOST:$DB_PORT..."
        sleep 1
    done
fi

echo "[entrypoint] Checking Composer dependencies..."
composer install --no-interaction --prefer-dist --optimize-autoloader

echo "[entrypoint] Checking Node dependencies..."
if [ ! -d "node_modules" ]; then
    npm ci || npm install
fi

echo "[entrypoint] Building Frontend Assets..."
npm run build

echo "[entrypoint] Running Database Migrations..."
php bin/console doctrine:migrations:migrate --no-interaction --allow-no-migration || echo "[entrypoint] Migrations failed or no migrations to run"

echo "[entrypoint] Clearing Cache..."
php bin/console cache:clear
php bin/console cache:warmup

echo "[entrypoint] Installing Assets..."
php bin/console assets:install public

echo "[entrypoint] Ensuring writable cache/logs/uploads"
mkdir -p var/cache var/log public/uploads/adjuntos
chown -R www-data:www-data var public/uploads || true
chmod -R 775 var public/uploads || true

# Make PHP-FPM listen on all interfaces so Nginx (separate container) can reach it
sed -i 's/^listen = .*/listen = 0.0.0.0:9000/' /usr/local/etc/php-fpm.d/www.conf
# Mark bootstrap complete to skip heavy steps on restarts
touch /tmp/bootstrapped
echo "[entrypoint] Starting PHP-FPM"
exec php-fpm
