#!/bin/bash
# Send an HTML message file to Basti's Telegram. Prints only the API result JSON.
# usage: send.sh <file>
set -euo pipefail
FILE=${1:?usage: send.sh <file>}
ENV=/opt/data/.env
tok=$(grep -m1 '^TELEGRAM_BOT_TOKEN=' "$ENV" | cut -d= -f2- | tr -d "\"'")
chat=$(grep -m1 '^TELEGRAM_HOME_CHANNEL=' "$ENV" | cut -d= -f2- | tr -d "\"'")
thread=${TELEGRAM_HOME_CHANNEL_THREAD_ID:-}
[ -n "$tok" ] && [ -n "$chat" ] || { echo "missing TELEGRAM_BOT_TOKEN/TELEGRAM_HOME_CHANNEL in $ENV" >&2; exit 1; }

args=(-sS -X POST "https://api.telegram.org/bot${tok}/sendMessage" -d "chat_id=$chat")
if [ -n "$thread" ]; then args+=(-d "message_thread_id=$thread"); fi
args+=(-d parse_mode=HTML)

send() {
  curl "${args[@]}" --data-urlencode "text=$1" \
    | jq -c '{ok, error_code, description, message_id: .result.message_id}'
}

msg=$(cat "$FILE")
if [ ${#msg} -le 4000 ]; then
  send "$msg"
else
  chunk=""
  while IFS= read -r line || [ -n "$line" ]; do
    if [ $(( ${#chunk} + ${#line} + 1 )) -gt 4000 ]; then
      send "$chunk"; chunk=""
    fi
    chunk+="$line"$'\n'
  done <<< "$msg"
  if [ -n "$chunk" ]; then send "$chunk"; fi
fi
