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

tg_pid=""

stop_children() {
  if [ -n "$tg_pid" ] && kill -0 "$tg_pid" 2>/dev/null; then
    kill "$tg_pid"
    wait "$tg_pid" 2>/dev/null || true
  fi
}

trap stop_children INT TERM EXIT

if [ -n "${TELEGRAM_API_ID:-}" ] && [ -n "${TELEGRAM_API_HASH:-}" ]; then
  mkdir -p "${TELEGRAM_WORK_DIR:-/var/lib/telegram-bot-api}" "${TELEGRAM_TEMP_DIR:-/tmp/telegram-bot-api}"
  telegram-bot-api \
    --api-id="${TELEGRAM_API_ID}" \
    --api-hash="${TELEGRAM_API_HASH}" \
    --dir="${TELEGRAM_WORK_DIR:-/var/lib/telegram-bot-api}" \
    --temp-dir="${TELEGRAM_TEMP_DIR:-/tmp/telegram-bot-api}" \
    --http-port="${TELEGRAM_HTTP_PORT:-8081}" \
    --local &
  tg_pid="$!"
  echo "Started local Telegram Bot API on 127.0.0.1:${TELEGRAM_HTTP_PORT:-8081}"
else
  echo "TELEGRAM_API_ID/TELEGRAM_API_HASH are not set; local Telegram Bot API is disabled"
fi

exec "$@"
