#!/bin/sh
# Check that the installed service is advertised over mDNS via Avahi.
set -eu

# The service may still be starting on a freshly installed system.
i=0
until dbus-send --system --print-reply=literal --dest=org.freedesktop.DBus \
	/org/freedesktop/DBus org.freedesktop.DBus.NameHasOwner \
	string:org.gnome.ShairportSync 2>/dev/null | grep -q 'boolean true'; do
	i=$((i + 1))
	if [ "$i" -ge 150 ]; then
		echo "FAIL: shairport-sync did not appear on the system bus" >&2
		journalctl -u shairport-sync --no-pager >&2 || true
		exit 1
	fi
	sleep 0.2
done

protocol="$(dbus-send --system --print-reply=literal --dest=org.gnome.ShairportSync \
	/org/gnome/ShairportSync org.freedesktop.DBus.Properties.Get \
	string:org.gnome.ShairportSync string:Protocol | sed 's/^ *variant *//')"
echo "Protocol: $protocol"

browse() { # browse SERVICE-TYPE PATTERN
	# Registration with Avahi can lag behind the D-Bus interface, so retry.
	for _ in 1 2 3 4 5 6 7 8 9 10; do
		if avahi-browse -rtp "$1" | grep '^=' | grep -q "$2"; then
			avahi-browse -rtp "$1" | grep '^='
			return 0
		fi
		sleep 2
	done
	echo "FAIL: no resolvable $1 service from Shairport Sync" >&2
	avahi-browse -atp >&2 || true
	exit 1
}

echo "browsing for _raop._tcp..."
browse _raop._tcp '"am=ShairportSync"'

if [ "$protocol" = "AirPlay 2" ]; then
	echo "browsing for _airplay._tcp..."
	browse _airplay._tcp '"model=ShairportSync"'
fi
echo "OK"
