#!/usr/bin/env bash
# CluPilot container entrypoint.
# On a fresh checkout the bind mount carries no vendor/ or node_modules/ (both
# are gitignored). The `app` container installs them once as the mapped user;
# dependent daemons (reverb/queue/scheduler) wait until vendor/ exists before
# starting, so they don't crash-loop. When deps already exist, this is a no-op.
set -e
cd /var/www/html

# run a command as the image's app user (www-data == HOST_UID) with a writable HOME
www() { su -s /bin/sh www-data -c "cd /var/www/html && HOME=/tmp $*"; }

role="tool"
if [ "${1:-}" = "supervisord" ]; then
    role="app"
elif printf '%s ' "$@" | grep -qE 'reverb:start|queue:work|schedule:work'; then
    role="daemon"
fi

if [ "$role" = "app" ]; then
    # A container that was killed leaves public/hot behind, and Laravel then
    # serves @vite from a dev server that is not running — every asset 404s.
    # Vite recreates the file when it actually starts.
    rm -f public/hot
    [ -f vendor/autoload.php ]   || www "composer install --no-interaction --prefer-dist --no-progress"
    [ -x node_modules/.bin/vite ] || www "npm install --no-fund --no-audit"
    # With the Vite dev server off (the default for domain/HTTPS operation),
    # @vite needs the built manifest — and public/build is gitignored, so a
    # fresh checkout has none. Build it once instead of failing every page with
    # ViteManifestNotFoundException.
    if [ "${VITE_AUTOSTART:-false}" != "true" ] && [ ! -f public/build/manifest.json ]; then
        # Non-fatal: a broken build must not wedge the container in a restart
        # loop where the logs are unreachable — nginx still comes up and the
        # error is visible in the browser.
        www "npm run build" || echo "clupilot-entrypoint: asset build FAILED — run 'npm run build' manually"
    fi
    if [ -f .env ] && ! grep -qE '^APP_KEY=.+' .env; then
        www "php artisan key:generate --force" || true
    fi
elif [ "$role" = "daemon" ]; then
    n=0
    until [ -f vendor/autoload.php ]; do
        n=$((n + 1)); [ "$n" -gt 150 ] && break
        echo "clupilot-entrypoint: waiting for vendor/ (app container installing deps) …"
        sleep 2
    done
fi

exec "$@"
