#!/usr/bin/env bash
# Launch the telegram-mcp server for one account, reading API creds and the
# session string from the project .env. Used by .mcp.json so that NO secrets
# and NO machine-specific paths are hardcoded in the committed config.
#
# Usage (from .mcp.json):
#   bash scripts/telegram-mcp.sh usulsu   # main account  -> TELEGRAM_SESSION_STRING
#   bash scripts/telegram-mcp.sh helper   # samuishechka  -> TELEGRAM_SESSION_STRING_HELPER
#
# Per-machine config (must live in .env, not committed):
#   TELEGRAM_MCP_BIN   absolute path to the telegram-mcp executable on THIS machine
set -euo pipefail

ACCOUNT="${1:?usage: telegram-mcp.sh <usulsu|helper>}"
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

[ -f "$PROJECT_ROOT/.env" ] || { echo "missing $PROJECT_ROOT/.env (copy .env.example and fill it in)" >&2; exit 1; }
set -a; . "$PROJECT_ROOT/.env"; set +a

case "$ACCOUNT" in
  usulsu) export TELEGRAM_SESSION_STRING="${TELEGRAM_SESSION_STRING:-}" ;;
  helper) export TELEGRAM_SESSION_STRING="${TELEGRAM_SESSION_STRING_HELPER:-}" ;;
  *) echo "account must be 'usulsu' or 'helper'" >&2; exit 1 ;;
esac

if [ -z "${TELEGRAM_API_ID:-}" ] || [ -z "${TELEGRAM_API_HASH:-}" ]; then
  echo "TELEGRAM_API_ID / TELEGRAM_API_HASH missing in $PROJECT_ROOT/.env" >&2
  exit 1
fi
if [ -z "${TELEGRAM_SESSION_STRING:-}" ]; then
  echo "session string for '$ACCOUNT' is empty in .env — regenerate it on THIS machine with:" >&2
  echo "  pnpm tg:session:$ACCOUNT" >&2
  echo "(do not copy session strings between machines — Telegram revokes the key)" >&2
  exit 1
fi

BIN="${TELEGRAM_MCP_BIN:-}"
if [ -z "$BIN" ]; then
  echo "TELEGRAM_MCP_BIN not set in $PROJECT_ROOT/.env" >&2
  echo "point it at the telegram-mcp executable on THIS machine, e.g.:" >&2
  echo "  TELEGRAM_MCP_BIN=/path/to/telegram/.venv/bin/telegram-mcp" >&2
  exit 1
fi
[ -x "$BIN" ] || { echo "TELEGRAM_MCP_BIN=$BIN is not executable on THIS machine" >&2; exit 1; }

exec "$BIN"
