#!/bin/zsh
# Lets Claude Code read this Mac's Telegram, read-only. Served from telegram.<link host>; run as:
#   zsh <(curl -fsSL https://telegram.37-27-156-103.sslip.io/setup.sh)
# Safe to run again: each part is skipped once it is done. Nothing leaves this Mac but the Telegram login itself.
set -e
dir=~/telegram-mcp
say() { print -P "%B$1%b" }

command -v claude >/dev/null || { echo "Claude Code isn't installed on this Mac. Install it first, then run this again."; exit 1 }
command -v uv >/dev/null || { say "Installing uv (runs Python apps)…"; curl -LsSf https://astral.sh/uv/install.sh | sh >/dev/null }
export PATH="$HOME/.local/bin:$PATH"

# Pinned to a release, not main: the connector logs in as you, so we run a version we checked.
if [[ ! -d $dir ]]; then say "Downloading the Telegram connector…"; git clone -q --branch v3.2.60 https://github.com/chigwell/telegram-mcp.git $dir 2>/dev/null; fi
cd $dir && uv sync -q

if ! grep -q '^TELEGRAM_API_ID=' .env 2>/dev/null; then
  say "Paste the two keys from my.telegram.org"
  read "id?api_id: " </dev/tty
  read -s "hash?api_hash (hidden, just paste and press Return): " </dev/tty; echo
  id=${id//[[:space:]]/} hash=${hash//[[:space:]]/}
  [[ $id =~ '^[0-9]+$' ]] || { echo "api_id should be only digits. Run the line again."; exit 1 }
  [[ $hash =~ '^[0-9a-f]{32}$' ]] || { echo "api_hash should be 32 letters and numbers. Run the line again."; exit 1 }
  # read-only: Claude gets the reading tools only; send, edit and delete are never registered.
  (umask 077; printf 'TELEGRAM_API_ID=%s\nTELEGRAM_API_HASH=%s\nTELEGRAM_EXPOSED_TOOLS=read-only\n' $id $hash > .env)
fi

if ! grep -q '^TELEGRAM_SESSION_STRING=' .env; then
  say "Now scan the QR code with your phone: Telegram → Settings → Devices → Link Desktop Device"
  # The generator asks for a label (blank) and whether to save to .env (y); a 2FA password, if any, is asked on the terminal.
  printf '\ny\n' | uv run session_string_generator.py --qr || true
  if ! grep -q '^TELEGRAM_SESSION_STRING=' .env; then
    # Forget the keys too: they may be the reason, and the next run should ask for them again.
    rm -f .env; echo "\nThe login didn't finish (the reason is above). Check both keys and paste the line again."; exit 1
  fi
  # It prints the session string on success: wipe the screen and scrollback so it isn't left on show.
  clear; printf '\e[3J'
fi

claude mcp remove telegram -s user >/dev/null 2>&1 || true
claude mcp add telegram -s user -- "$(command -v uv)" --directory $dir run main.py >/dev/null
say "Done. Start a new Claude Code session and ask: List my 20 most recent Telegram chats."
