#!/bin/sh
# Start the Haematite MCP server over stdio for a plugin session.
#
# The service:   HAEMATITE_CONFIG (the running service's serve.json), else
#                ~/.config/haematite/serve.json.
# The binary:    HAEMATITE_BIN, else haematite on PATH.
# The Lys pass every call presents, the first that is set:
#   HAEMATITE_PASS_FILE                      a file holding a pass;
#   HAEMATITE_LYS_AGENT with HAEMATITE_LYS_ISSUER and one of
#     HAEMATITE_KEY_FILE                     the agent's key file,
#     HAEMATITE_CREDENTIAL_FILE              the agent's credential file,
#     HAEMATITE_RUN_PASS_ENV                 the name of a variable holding a run pass
#                                            (LYS_AGENT_PASS for a seat Lys started).
# With none set, a store behind Lys refuses every call pass_missing; this script says so.
config="${HAEMATITE_CONFIG:-$HOME/.config/haematite/serve.json}"
binary="${HAEMATITE_BIN:-haematite}"
if [ ! -f "$config" ]; then
  echo "haematite_mcp_config_missing: no service configuration at $config; set HAEMATITE_CONFIG to the running service's serve.json" >&2
  exit 78
fi
if ! command -v "$binary" >/dev/null 2>&1; then
  echo "haematite_mcp_binary_missing: $binary is not on PATH; install haematite-cli or set HAEMATITE_BIN" >&2
  exit 127
fi
if [ -n "$HAEMATITE_PASS_FILE" ]; then
  exec "$binary" mcp --config "$config" --pass-file "$HAEMATITE_PASS_FILE"
fi
if [ -n "$HAEMATITE_LYS_AGENT" ]; then
  if [ -z "$HAEMATITE_LYS_ISSUER" ]; then
    echo "haematite_mcp_issuer_missing: HAEMATITE_LYS_AGENT is set but HAEMATITE_LYS_ISSUER (the Lys origin) is not" >&2
    exit 78
  fi
  if [ -n "$HAEMATITE_KEY_FILE" ]; then
    exec "$binary" mcp --config "$config" --lys-agent "$HAEMATITE_LYS_ISSUER" "$HAEMATITE_LYS_AGENT" --key-file "$HAEMATITE_KEY_FILE"
  fi
  if [ -n "$HAEMATITE_CREDENTIAL_FILE" ]; then
    exec "$binary" mcp --config "$config" --lys-agent "$HAEMATITE_LYS_ISSUER" "$HAEMATITE_LYS_AGENT" --credential-file "$HAEMATITE_CREDENTIAL_FILE"
  fi
  if [ -n "$HAEMATITE_RUN_PASS_ENV" ]; then
    exec "$binary" mcp --config "$config" --lys-agent "$HAEMATITE_LYS_ISSUER" "$HAEMATITE_LYS_AGENT" --run-pass-env "$HAEMATITE_RUN_PASS_ENV"
  fi
  echo "haematite_mcp_agent_proof_missing: HAEMATITE_LYS_AGENT is set; set HAEMATITE_KEY_FILE, HAEMATITE_CREDENTIAL_FILE or HAEMATITE_RUN_PASS_ENV" >&2
  exit 78
fi
echo "haematite_mcp_no_pass: no Lys pass is configured; a store behind Lys refuses every call pass_missing (set HAEMATITE_LYS_AGENT and its proof, or HAEMATITE_PASS_FILE)" >&2
exec "$binary" mcp --config "$config"
