#!/bin/sh
# hal0-hermes — env-injecting wrapper around the hal0-managed Hermes venv.
#
# Post-ADR-0012 (no Bearer auth), the wrapper's sole job is to set:
#
#   HERMES_HOME    — pins Hermes's state dir under hal0's tree so a
#                    `hermes reset` or upstream config-rewrite stays
#                    contained.
#   HAL0_AGENT_ID  — surfaced on outbound MCP calls and echoed back as
#                    the `client_id` for Cognee's `private:<client_id>`
#                    namespace. The hal0 MCP mount resolves the caller's
#                    identity + `--private` toggle straight off the live
#                    MCP request headers (see `hal0.api.mcp_mount`).
#
# It then execs the hal0-managed venv's `hermes` binary. The venv
# lives at /var/lib/hal0/venvs/hermes/ (hard-pinned in
# installer/agents/hermes/requirements.txt). HAL0_HERMES_BIN overrides
# when the venv lives elsewhere.
#
# `--hal0-ready` is the smoke-test sentinel the installer pings to
# verify the wrapper is on PATH WITHOUT spawning upstream `hermes`.
#
# An optional outbound-credentials env file at
# /var/lib/hal0/secrets/agents/hermes.env (mode 0600) is sourced when
# present. Post-ADR-0012 this holds HF token + external MCP tokens
# only — never a hal0 Bearer.

set -eu

HERMES_HOME="${HERMES_HOME:-/var/lib/hal0/.hermes}"
HAL0_AGENT_ID="${HAL0_AGENT_ID:-hermes-agent}"
HAL0_HERMES_BIN="${HAL0_HERMES_BIN:-/var/lib/hal0/venvs/hermes/bin/hermes}"
HAL0_HERMES_SECRETS="${HAL0_HERMES_SECRETS:-/var/lib/hal0/secrets/agents/hermes.env}"

export HERMES_HOME
export HAL0_AGENT_ID

# Source the outbound-credentials file when present (HF / external MCP
# tokens per ADR-0013). Optional — bootstrap may run without one.
if [ -r "$HAL0_HERMES_SECRETS" ]; then
    set -a
    # shellcheck disable=SC1090
    # (path is operator-controlled by design)
    . "$HAL0_HERMES_SECRETS"
    set +a
fi

case "${1:-}" in
    --hal0-ready) exit 0 ;;
esac

if [ ! -x "$HAL0_HERMES_BIN" ]; then
    printf 'hal0-hermes: venv binary missing at %s\n' "$HAL0_HERMES_BIN" >&2
    printf '  Run `hal0 agent bootstrap hermes` to provision.\n' >&2
    exit 127
fi

exec "$HAL0_HERMES_BIN" "$@"
