#!/bin/sh
set -eu

address_file=/etc/romulus-bluetooth-address
address="$(tr -d '[:space:]' < "$address_file")"
case "$address" in
	[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]:[0-9A-Fa-f][0-9A-Fa-f]) ;;
	*)
		echo "Invalid Bluetooth address in $address_file" >&2
		exit 1
		;;
esac

attempt=0
while [ "$attempt" -lt 60 ] && [ ! -e /sys/class/bluetooth/hci0 ]; do
	attempt=$((attempt + 1))
	sleep 0.5
done

if [ ! -e /sys/class/bluetooth/hci0 ]; then
	echo "hci0 did not appear" >&2
	exit 1
fi

if btmgmt info 2>/dev/null | grep -Fqi "$address"; then
	exit 0
fi

# The UART HCI device appears slightly before the raw QCA controller accepts
# management commands. Keep bluetooth.service ordered behind this retry loop.
attempt=0
last_error=""
while [ "$attempt" -lt 60 ]; do
	if output="$(btmgmt -i hci0 public-addr "$address" 2>&1)"; then
		printf '%s\n' "$output"
		exit 0
	fi
	last_error="$output"
	attempt=$((attempt + 1))
	sleep 0.5
done

printf '%s\n' "$last_error" >&2
exit 1
