#!/bin/sh

notify () {
	notify-send -i "$icon_path" -e -h "string:x-canonical-private-synchronous:${0##*/}" "[$1] ${2}" "$3"
}

env_file="${XDG_CONFIG_HOME:-$HOME/.config}/.env"
. "$env_file"

ntfy_creds load

token="$(printf 'Basic %s' "$(printf ':%s' "$NTFY_TOKEN" | base64)" | base64 | tr -d '=')"
icon_path="$(dirname "$0")/ntfy.png"

trap "ntfy_creds unload" EXIT
trap "ntfy_creds unload; exit 1" INT HUP

websocat --no-close "wss://${NTFY_URL#https://}/$NTFY_TOPIC_LISTEN/ws?auth=$token" | while IFS= read -r line; do 
	title=$(printf '%s' "$line" | sed -nE 's|.*,"title":"([^"]*)",.*|\1|p')
	topic=$(printf '%s' "$line" | sed -nE 's|.*,"topic":"([^"]*)",?.*|\1|p')
	message=$(printf '%s' "$line" | sed -nE 's|.*,"message":"([^"]*)",.*|\1|p')
	printf '%s' "$line" | grep -q '"open"' && notify "NTFY" "Listening" "$topic"
	[ -z "$message" ] || notify "$topic" "${title:-NO TITLE}" "$message"
done
