#!/bin/sh

# SNAC2TG
#
# posts a snac2/ActivityPub JSON file to a Telegram channel or chat
# requires a bot token that could be obtained via [t.me/BotFather]
# 
# can be used to set up an automatic repost system like so:
#	$ inotifyd snac2tg /snac/user/me/public:ny
#
# made by @k60@soundhunte.rs on February 18, 2026
# published under MIT license

if [ $# -eq 1 ]; then
    # humans mostly use the script interactively with one argument
    FILE="$1"
elif [ $# -eq 3 ]; then
    # busybox inotifyd calls the script with three arguments: event dir path
    FILE="$2/$3"
else
    exit 255
fi

# configure these
BOT="here goes your token obtained from t.me/BotFather"
CHAT="@ksixtyisonline"

# keep these as they are
MAX_PICTURE=1024
MAX_MESSAGE=4096
TGAPI="https://api.telegram.org/bot${BOT}"

get() { 
	jq -r "$1 // empty" "$FILE" 
}

fits() { 
	# character limit is just that--character, not markup;
	# so we strip all HTML tags for a bit better length estimate
	[ $(printf '%s' "${1}" | sed 's,<[^>]+>,,g' | wc -c) -le "$2" ] 
}

[ "$(get '.inReplyTo')" ] && exit 0 # abort if this note is a reply

# telegram disallows <br>, <span>...
# and God knows what else but I have only seen these in snac2 markup
text=$(get '.content' | sed 's,<br>,\n,g; s,<[/]*span[^>]*>,,g')
link=$(get '.url' | sed 's,https://,,')

# a post is its text + a link, if it fits into character limit
# otherwise, it's just a link (truncation occurs below)
post=$(printf '%s\n\n%s' "$text" "$link")

att_kind=$(get '.attachment[0].mediaType')
att_link=$(get '.attachment[0].url')

while true; do
	case "$att_kind" in
		image/*)
			$(fits "$text_raw" $MAX_PICTURE) || post="$link"

			img_path="/tmp/$(basename "$att_link")"
			wget -q -O "$img_path" "$att_link" || (rm "$img_path"; continue)

			curl -sX POST "${TGAPI}/sendPhoto" \
				--form-string "chat_id=${CHAT}" \
				--form-string "caption=${post}" \
				--form        "photo=@${img_path}" | jq && break
			;;
		*)
			$(fits "$text_raw" $MAX_MESSAGE) || post="$link"
			curl -sX POST "${TGAPI}/sendMessage" \
				--form-string "chat_id=${CHAT}" \
				--form-string "text=${post}" \
				--form-string "parse_mode=HTML" \
				--form-string "disable_web_page_preview=true" | jq && break
			;;
	esac;
done
