#!/bin/sh
set -e

# ──────────────────────────────────────────────────────────────
# Run full initialization only for the main app (php-fpm).
# Queue workers skip this and start immediately.
# ──────────────────────────────────────────────────────────────
if [ "$1" = "php-fpm" ]; then

    # 1. Sync public/ from image on every boot so any changed files are picked up on redeploy.
    # public-init/ never contains storage/, so the storage symlink is not affected.
    #
    # cp only *adds*, so anything the volume ever picked up outlives every
    # rebuild. Two things must be dropped first or the site serves the wrong
    # assets indefinitely:
    #   - public/hot, the Vite dev-server marker. While it exists @vite points
    #     every tag at localhost:5173 and the page loads no CSS or JS.
    #   - public/build, whose filenames are content-hashed. Old hashes are not
    #     overwritten by the new ones, they simply accumulate next to a
    #     manifest that no longer names them.
    echo "[entrypoint] Syncing public/ from image..."
    rm -f /var/www/public/hot
    rm -rf /var/www/public/build
    cp -r /var/www/public-init/. /var/www/public/
    chown -R www-data:www-data /var/www/public

    # 2. Ensure all storage directories exist (volume starts empty)
    mkdir -p \
        /var/www/storage/app/public \
        /var/www/storage/framework/cache/data \
        /var/www/storage/framework/sessions \
        /var/www/storage/framework/views \
        /var/www/storage/framework/testing \
        /var/www/storage/logs
    chown -R www-data:www-data /var/www/storage /var/www/bootstrap/cache

    # 3. Wait for MySQL to accept connections
    echo "[entrypoint] Waiting for MySQL..."
    RETRIES=30
    until php -r "
        new PDO(
            'mysql:host=' . getenv('DB_HOST') . ';port=' . (getenv('DB_PORT') ?: 3306),
            getenv('DB_USERNAME'),
            getenv('DB_PASSWORD')
        );
    " 2>/dev/null; do
        RETRIES=$((RETRIES - 1))
        if [ "$RETRIES" -eq 0 ]; then
            echo "[entrypoint] ERROR: Could not connect to MySQL. Aborting."
            exit 1
        fi
        sleep 2
    done
    echo "[entrypoint] MySQL is ready."

    # 4. Run database migrations
    # Non-fatal: z_laravel_framework.sql pre-marks bundled migrations as done.
    # Genuinely new migrations (Round 2 scoring etc.) run idempotently via
    # Schema::hasColumn guards.
    php artisan migrate --force --no-interaction \
        && echo "[entrypoint] Migrations complete." \
        || echo "[entrypoint] Some migrations skipped (tables already exist from imported dump)."

    # 5. Seed static lookup data. All seeders are idempotent (firstOrCreate /
    # upsert), safe to run on every boot.
    php artisan db:seed --class=ColumnTooltipSeeder --force --no-interaction \
        && echo "[entrypoint] ColumnTooltip seed complete." \
        || echo "[entrypoint] ColumnTooltip seed failed (non-fatal)."

    php artisan db:seed --class=AdminUserSeeder --force --no-interaction \
        && echo "[entrypoint] AdminUser seed complete." \
        || echo "[entrypoint] AdminUser seed failed (non-fatal)."

    # 6. Create storage symlink (public disk)
    php artisan storage:link --no-interaction 2>/dev/null || true

    # 7. Optional: recompute all charity scores on boot. Off by default because
    # it takes ~14 min on 2.88M rows. Set RESCORE_ON_BOOT=true after deploying
    # a calculator change or after a fresh data import to backfill scores.
    if [ "${RESCORE_ON_BOOT:-false}" = "true" ]; then
        echo "[entrypoint] RESCORE_ON_BOOT=true — running charities:rescore (may take ~15 min)..."
        php artisan charities:rescore \
            && echo "[entrypoint] Rescore complete." \
            || echo "[entrypoint] Rescore failed (non-fatal)."
    fi

    # 8. Warm caches for production
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache

fi

echo "[entrypoint] Starting: $*"
exec "$@"
