#!/usr/bin/env bash
# notify-telegram.sh — post a Telegram message for a CI stage.
#
# Usage: notify-telegram.sh [--dry-run] <start|ok|fail> <stage> [<extra-context>]
#
# Env (required unless --dry-run):
#   TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
# Env (always read for context):
#   GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_SERVER_URL, GITHUB_SHA, GITHUB_WORKFLOW
set -euo pipefail

DRY_RUN=0
if [ "${1:-}" = "--dry-run" ]; then
  DRY_RUN=1
  shift
fi

VERB="${1:-}"
STAGE="${2:-}"
EXTRA="${3:-}"
LOG_PATH="${4:-}"

case "$VERB" in
  start|ok|fail) ;;
  *) echo "usage: $0 [--dry-run] <start|ok|fail> <stage> [<extra-context>]" >&2; exit 2 ;;
esac

[ -n "$STAGE" ] || { echo "usage: $0 [--dry-run] <start|ok|fail> <stage> [<extra-context>]" >&2; exit 2; }

if [ "$DRY_RUN" -eq 0 ]; then
  if [ -z "${TELEGRAM_BOT_TOKEN:-}" ] || [ -z "${TELEGRAM_CHAT_ID:-}" ]; then
    echo "notify-telegram: TELEGRAM_BOT_TOKEN/TELEGRAM_CHAT_ID unset — skipping" >&2
    exit 0
  fi
fi

REPO="${GITHUB_REPOSITORY:-unknown/repo}"
RUN_ID="${GITHUB_RUN_ID:-0}"
SERVER="${GITHUB_SERVER_URL:-https://git.gnerim.ru}"
SHA="${GITHUB_SHA:-unknown}"
SHORT_SHA="${SHA:0:7}"
RUN_URL="${SERVER}/${REPO}/actions/runs/${RUN_ID}"

case "$VERB" in
  start) ICON="🚀"; HEAD="${ICON} ${STAGE} started" ;;
  ok)    ICON="✅"; HEAD="${ICON} ${STAGE} passed" ;;
  fail)  ICON="❌"; HEAD="${ICON} ${STAGE} FAILED${EXTRA:+ at step \"${EXTRA}\"}" ;;
esac

# Body is plain text (no HTML escaping needed for our content).
BODY="${HEAD}
commit: ${SHORT_SHA}
gitea run: ${RUN_URL}"

if [ "$VERB" = "fail" ] && [ -n "$LOG_PATH" ] && [ -f "$LOG_PATH" ]; then
  TAIL_LINES=$(tail -n 30 "$LOG_PATH")
  TAIL_COUNT=$(printf '%s\n' "$TAIL_LINES" | wc -l | tr -d ' ')
  BODY="${BODY}

last ${TAIL_COUNT} lines:
${TAIL_LINES}"
fi

if [ "$DRY_RUN" -eq 1 ]; then
  printf '%s\n' "$BODY"
  exit 0
fi

# Send via curl. Use --data-urlencode to avoid encoding pitfalls.
curl -fsS -X POST \
  "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
  --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \
  --data-urlencode "text=${BODY}" \
  --data-urlencode "disable_web_page_preview=true" \
  >/dev/null
