#!/usr/bin/env sh
set -eu

# Connector-owned Telegram credential formatter. The Host injects the selected
# Bot token only into this process as TG_BOT_TOKEN. The token is never accepted
# in argv and this helper never reads Telegram's legacy singleton vault key.
case "${1:-}" in
  credential-token)
    [ -n "${TG_BOT_TOKEN:-}" ] || {
      printf '%s\n' '[cteno-telegram-connector] TG_BOT_TOKEN is missing' >&2
      exit 1
    }
    API="${CTENO_TELEGRAM_API_BASE:-https://api.telegram.org}"
    PROXY="${TG_BOT_PROXY:-}"
    if command -v jq >/dev/null 2>&1; then
      jq -cn --arg botToken "$TG_BOT_TOKEN" --arg apiBase "$API" --arg proxy "$PROXY" \
        '{botToken:$botToken,apiBase:$apiBase,proxy:$proxy}'
    else
      # Tokens cannot contain JSON metacharacters in Telegram's Bot API format;
      # still reject unexpected values rather than implementing unsafe escaping.
      case "$TG_BOT_TOKEN$API$PROXY" in
        *'"'*|*'\\'*|*'
'*) exit 1 ;;
      esac
      printf '{"botToken":"%s","apiBase":"%s","proxy":"%s"}\n' \
        "$TG_BOT_TOKEN" "$API" "$PROXY"
    fi
    ;;
  *)
    printf '%s\n' 'usage: cteno-telegram-connector credential-token' >&2
    exit 2
    ;;
esac
