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

APP_RUNTIME_ENV="${APP_ENV:-dev}"

run_as_www_data() {
    if [ "$(id -u)" = "0" ]; then
        su -s /bin/sh www-data -c "$*"
        return
    fi

    sh -lc "$*"
}

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('Symfony\\Component\\Process\\Process') && 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
}

ensure_writable_runtime_dirs() {
    echo "[entrypoint] Ensuring writable runtime dirs"
    echo "[entrypoint] APP_ENV=${APP_RUNTIME_ENV} APP_DEBUG=${APP_DEBUG:-}"
    echo "[entrypoint] Current user: $(id -u):$(id -g)"

    mkdir -p \
        var/cache \
        var/log \
        public/uploads \
        public/uploads/adjuntos \
        var/cache/prod \
        var/cache/prod/doctrine \
        var/cache/prod/doctrine/orm \
        var/cache/prod/doctrine/orm/Proxies

    if [ "$(id -u)" = "0" ]; then
        chown -R www-data:www-data var/cache var/log public/uploads
    fi
    chmod -R ug+rwX var/cache var/log public/uploads

    ls -ld var/cache var/cache/prod var/log public/uploads || true

    if [ "${APP_RUNTIME_ENV}" = "prod" ]; then
        if ! run_as_www_data "test -w var/cache/prod/doctrine/orm/Proxies"; then
            echo "[entrypoint] Proxies directory is not writable by www-data. Reapplying runtime permissions."
            if [ "$(id -u)" = "0" ]; then
                chown -R www-data:www-data var/cache var/log public/uploads
            fi
            chmod -R ug+rwX var/cache var/log public/uploads
        fi

        if ! run_as_www_data "test -w var/cache/prod/doctrine/orm/Proxies"; then
            echo "[entrypoint] ERROR: var/cache/prod/doctrine/orm/Proxies is still not writable by www-data."
            ls -ld var/cache var/cache/prod var/cache/prod/doctrine var/cache/prod/doctrine/orm var/cache/prod/doctrine/orm/Proxies || true
            exit 1
        fi

        echo "[entrypoint] Proxies writable by www-data"
    fi

    echo "[entrypoint] Runtime dirs OK"
}

# Fast path: skip all bootstrap if SKIP_BOOTSTRAP=1
if [ "${SKIP_BOOTSTRAP:-0}" = "1" ]; then
    ensure_composer_dependencies
    ensure_writable_runtime_dirs
    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
    ensure_writable_runtime_dirs
    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..."
run_as_www_data "php bin/console cache:clear --env=${APP_RUNTIME_ENV} --no-debug"
run_as_www_data "php bin/console cache:warmup --env=${APP_RUNTIME_ENV} --no-debug"

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

ensure_writable_runtime_dirs

# 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
