#!/bin/sh
# Attach the UWE5622 (AW859A) Bluetooth controller on /dev/ttyBT0.
# With sprdbt_tty vendor_init=1 (default), "rfkill unblock" runs the vendor init.
# If the init fails, the switch stays blocked: exit 1, so systemd retries.
# With vendor_init=0, the vendor hciattach_opi does the init.
set -u
dev=/dev/ttyBT0
param=/sys/module/sprdbt_tty/parameters/vendor_init

rfkill unblock all

unblocked=0
for r in /sys/class/rfkill/rfkill*; do
	d="$(readlink "$r/device/driver" 2> /dev/null)"
	[ "${d##*/}" = "mtty" ] || continue
	[ "$(cat "$r/soft")" = "0" ] && [ "$(cat "$r/hard")" = "0" ] && unblocked=1
done
if [ "$unblocked" = "0" ]; then
	echo "aw859a-bt-attach: Bluetooth rfkill is blocked. Vendor init failed, see dmesg." >&2
	exit 1
fi

vendor_init=N
[ -r "$param" ] && vendor_init="$(cat "$param")"

if [ "$vendor_init" = "Y" ] && command -v btattach > /dev/null 2>&1; then
	exec btattach -B "$dev" -P h4
fi

if [ -x /usr/bin/hciattach_opi ]; then
	exec /usr/bin/hciattach_opi -n -s 1500000 "$dev" sprd
fi

echo "aw859a-bt-attach: btattach and hciattach_opi are missing." >&2
exit 1
