#!/bin/sh
# Agent Inbox Listener wrapper — sources the off-repo secrets env, then runs the IDLE daemon.
# Long-running: launched by com.alexandria.agent-listener (KeepAlive). Sources the same
# alexandria.env as the digests, so it shares IMAP_USER/IMAP_PASS (the agent mailbox's app
# password) and every inbox processor's config.
#   Override the env file with ALEXANDRIA_ENV=/path/to/alexandria.env
ENVFILE=""
for f in "$ALEXANDRIA_ENV" "$HOME/Library/Application Support/Alexandria/alexandria.env" "$HOME/Alexandria-secrets/alexandria.env" "$HOME/.config/alexandria/alexandria.env"; do
  if [ -n "$f" ] && [ -f "$f" ]; then ENVFILE="$f"; break; fi
done
if [ -z "$ENVFILE" ]; then
  echo "agent-listener.sh: no env file found. Create it with `alexandria secrets --set` (or set ALEXANDRIA_ENV)." >&2
  exit 1
fi
set -a; . "$ENVFILE"; set +a
DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
# The engine lives in the installed alexandria-vault package (docs/DEVAULT.md step 3),
# not in the vault: run it from $ALEXANDRIA_PYTHON if set (e.g. in alexandria.env), else
# the app venv the installer maintains, else whatever python3 has the package.
VAULT=$(CDPATH= cd -- "$DIR/../../.." && pwd)
APP_PY="$HOME/Library/Application Support/Alexandria/app/.venv/bin/python3"
if [ -n "$ALEXANDRIA_PYTHON" ]; then PY="$ALEXANDRIA_PYTHON"
elif [ -x "$APP_PY" ]; then PY="$APP_PY"
else PY="python3"; fi
exec "$PY" -m alexandria_vault.engine.agent_listener --vault "$VAULT"
