#!/bin/sh
#
# darnit-mcp-runner — invoked by the Claude Code plugin's mcpServers
# entry to start the darnit MCP server. Implements the FR-017 fallback
# chain because Claude Code plugin manifests don't support fallback
# natively.
#
# DARNIT_MCP_VERSION is set by plugin.json::mcpServers["darnit-mcp"].env.
# The version is pinned in lockstep with the parent darnit release.

set -eu

if [ -z "${DARNIT_MCP_VERSION:-}" ]; then
    echo "darnit-mcp-runner: DARNIT_MCP_VERSION env var is required but not set." >&2
    echo "If you are invoking this script directly (outside Claude Code), set it explicitly." >&2
    exit 64
fi

# Each `try_*` either exec's (replacing this process and letting the
# runner's stderr flow through to the user) or falls off the end without
# exec'ing. We must NOT wrap these calls in `2>/dev/null` at the call
# site, because that redirection would persist past the exec and swallow
# uvx/pipx's own error messages once they've taken over the process —
# which is the most common operational failure mode (uvx is installed
# but PyPI is unreachable, the pinned version is missing, etc.). The
# probe (`command -v`) uses its own narrow 2>/dev/null so the absence
# of a tool is silent, but the exec inherits the script's stderr.
try_uvx() {
    if command -v uvx >/dev/null 2>&1; then
        exec uvx --from "darnit-mcp==${DARNIT_MCP_VERSION}" darnit-mcp "$@"
    fi
}

try_pipx() {
    if command -v pipx >/dev/null 2>&1; then
        exec pipx run "darnit-mcp==${DARNIT_MCP_VERSION}" "$@"
    fi
}

try_uvx "$@"
try_pipx "$@"

cat >&2 <<EOF
darnit plugin: neither 'uvx' nor 'pipx' is available on PATH.

Install one of:
  - uv (provides uvx):  https://docs.astral.sh/uv/getting-started/installation/
  - pipx:               https://pipx.pypa.io/stable/installation/

Then restart Claude Code or reload the plugin.
EOF
exit 127
