#!/bin/sh
#
# bt-address HCI -- give a Bluetooth controller without an address of its
# own a stable one.  The WCN399x has no address in its NVM; Android takes it
# from the modem's NV, which Linux cannot read, and the phone's persist
# partition has none.  The kernel then keeps the controller "unconfigured"
# (btmgmt: missing options: public-address) and bluetoothd does not use it.
#
# The address is derived from the phone's serial number (androidboot.serialno,
# set by the bootloader), as pmOS's bootmac does: the first six bytes of
# sha256("bluetooth" serialno), made unicast and locally administered
# (02 in the first byte).  Same phone, same address, every boot.
#
# Run by the runit service bt-address once hci0 exists.

hci=${1:-hci0}
idx=${hci#hci}

serial=$(tr ' ' '\n' < /proc/cmdline | sed -n 's/^androidboot.serialno=//p' | head -n 1)
[ -n "$serial" ] || { echo "bt-address: no androidboot.serialno" >&2; exit 1; }

h=$(printf 'bluetooth%s' "$serial" | sha256sum | cut -c1-12)
b0=$(( (0x$(echo "$h" | cut -c1-2) & 0xfc) | 0x02 ))
addr=$(printf '%02x' "$b0"; echo "$h" | cut -c3-12 | sed 's/../:&/g')

# The address makes the kernel set the controller up a second time (power
# pulse, firmware download over the UART).  On the WCN399x, which carries
# WLAN too, that second setup failed in about one boot of five while the
# modem started the WLAN firmware (2026-11-08: "Frame reassembly failed
# (-84)", "Failed to send TLV segment (-110)", no controller).  So: wait
# for WLAN (wlan0, at most 30 s), set the address, and if the controller
# does not come up, probe it again from scratch -- unbind and bind its
# UART driver -- and set the address again; three attempts.

wait_for() {	# wait_for CMD...: up to 15 s for CMD to succeed
	_j=0
	while ! "$@" 2>/dev/null; do
		_j=$((_j + 1)); [ "$_j" -le 30 ] || return 1
		sleep 0.5
	done
}
asks_address() {
	btmgmt --index "$idx" config 2>/dev/null | grep -q 'missing options:.*public-address'
}
configured() {
	btmgmt info 2>/dev/null | grep -q "^$hci:"
}

configured && exit 0		# it has an address of its own
wait_for asks_address || exit 0	# not a controller that wants one

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

dev=$(basename "$(readlink -f "/sys/class/bluetooth/$hci/device")")
drv=$(readlink -f "/sys/class/bluetooth/$hci/device/driver")

try=1
while :; do
	btmgmt --index "$idx" public-addr "$addr" >/dev/null 2>&1
	if wait_for configured; then
		echo "bt-address: $hci $addr (attempt $try)" > /dev/kmsg
		exit 0
	fi
	[ "$try" -lt 3 ] && [ -n "$drv" ] || break
	echo "bt-address: $hci did not come up, probing it again" > /dev/kmsg
	echo "$dev" > "$drv/unbind"
	sleep 1
	echo "$dev" > "$drv/bind"
	wait_for asks_address || break
	try=$((try + 1))
done
echo "bt-address: $hci not up after $try attempts" > /dev/kmsg
exit 1
