#!/bin/sh
set -eu

mode="${1:-api}"

# Ensure the SQLite data dir exists when DB_SQLITE_PATH is configured.
if [ -n "${DB_SQLITE_PATH:-}" ]; then
    sqlite_dir="$(dirname "$DB_SQLITE_PATH")"
    mkdir -p "$sqlite_dir"
fi

case "$mode" in
    api)
        # Provision UI_SERVICE_TOKEN in api_tokens before serving. Idempotent;
        # logs a warning and skips if the env var is empty (early bring-up).
        cd /app
        php bin/console auth:bootstrap-service-token || \
            echo "warning: auth:bootstrap-service-token failed; continuing anyway" >&2
        exec frankenphp run --config /etc/Caddyfile
        ;;
    migrate)
        cd /app
        # Empty migrations dir is fine — phinx exits 0 with "no migrations to run".
        exec vendor/bin/phinx migrate --configuration=config/phinx.php
        ;;
    *)
        echo "Unknown mode: $mode" >&2
        echo "Usage: entrypoint.sh [api|migrate]" >&2
        exit 1
        ;;
esac
