#!/usr/bin/env bash
# Send a Telegram message for the getBible API server.
#
#   getbible-notify LEVEL TITLE [BODY]
#
# LEVEL is one of info, start, ok, warn, fail and only picks the emoji.
# Reads /etc/getbible/telegram.conf (or $GB_TELEGRAM_CONF). Exits 0 when
# Telegram is disabled so callers never fail because of a notification.

set -uo pipefail

CONF="${GB_TELEGRAM_CONF:-/etc/getbible/telegram.conf}"
if [[ "$CONF" == /etc/getbible/telegram.conf && -f /run/getbible/telegram.conf ]]; then
    CONF=/run/getbible/telegram.conf
fi
LEVEL="${1:-info}"
TITLE="${2:-getBible}"
BODY="${3:-}"

conf_get() {
    local key="$1" line value=""
    [[ -f "$CONF" ]] || return 0
    while IFS= read -r line || [[ -n "$line" ]]; do
        [[ "$line" == "$key="* ]] && value="${line#"$key"=}"
    done < "$CONF"
    printf '%s' "$value"
}

[[ "$(conf_get TELEGRAM_ENABLED)" == true ]] || exit 0
TOKEN="$(conf_get TELEGRAM_BOT_TOKEN)"
CHAT="$(conf_get TELEGRAM_CHAT_ID)"
HOST="$(conf_get TELEGRAM_HOSTNAME)"
[[ -n "$TOKEN" && -n "$CHAT" ]] || exit 0
[[ -n "$HOST" ]] || HOST="$(hostname -f 2>/dev/null || hostname)"

case "$LEVEL" in
    start) EMOJI="🚀" ;;
    ok) EMOJI="✅" ;;
    warn) EMOJI="⚠️" ;;
    fail) EMOJI="🚨" ;;
    *) EMOJI="ℹ️" ;;
esac

escape() { sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g'; }

TEXT="$EMOJI <b>$(printf '%s' "$TITLE" | escape)</b>"
[[ -n "$BODY" ]] && TEXT="$TEXT
$(printf '%s' "$BODY" | escape)"
TEXT="$TEXT

🖥 $(printf '%s' "$HOST" | escape) · $(date -u +%Y-%m-%d\ %H:%M:%SZ)"

curl --silent --show-error --max-time 15 -o /dev/null \
    --data-urlencode "chat_id=$CHAT" \
    --data-urlencode "parse_mode=HTML" \
    --data-urlencode "disable_web_page_preview=true" \
    --data-urlencode "text=$TEXT" \
    "https://api.telegram.org/bot$TOKEN/sendMessage" \
    || { printf 'getbible-notify: telegram delivery failed\n' >&2; exit 0; }
exit 0
