#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
set -e

modprobe sprdbt_tty
rfkill unblock bluetooth

if [[ ! -r /sys/class/net/wlan0/address ]]; then
	echo "Wi-Fi address is unavailable; retry Bluetooth initialization later." >&2
	exit 1
fi

mac_file=/var/lib/bluetooth/torder-r10d-address
if [[ ! -s "${mac_file}" ]]; then
	install -d -m 700 /var/lib/bluetooth
	hash=$(printf '%s' "$(cat /etc/machine-id)-bt" | sha256sum)
	printf '02:%s:%s:%s:%s:%s\n' "${hash:2:2}" "${hash:4:2}" "${hash:6:2}" "${hash:8:2}" "${hash:10:2}" >"${mac_file}"
fi
read -r address <"${mac_file}"
[[ "${address}" =~ ^([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}$ ]]
# The helper derives its controller address from this service-local file.
mount --bind --read-only "${mac_file}" /sys/class/net/wlan0/address
exec /usr/bin/hciattach_opi -n -s 1500000 /dev/ttyBT0 sprd 1500000 flow "${address}"
