#!/bin/bash

set -e

# This script also runs on boards with no wireless module and an empty
# BT uart. Attaching there stalls shutdown. SDIO enumeration can finish
# after this script starts. No AIC device after 3 s means no BT chip.
# Vendor IDs: AIC8801 is 0x5449. AIC8800DC and AIC8800D80 are 0xc8a1.
aic_sdio=0
for _ in 1 2 3 4 5 6; do
	if grep -qxE '0x(5449|c8a1)' /sys/bus/sdio/devices/*/vendor 2>/dev/null; then
		aic_sdio=1
		break
	fi
	sleep 0.5
done
if [ "$aic_sdio" -eq 0 ]; then
	exit 0
fi

# HW Reset
if ! hciattach -r -s 1500000 /dev/ttyS1 any 1500000 flow nosleep > /dev/null 2>&1; then
	echo "Failed to reset HCI device" >&2
	exit 1
fi

# Kill process using device
sleep .50
pkill -f "/dev/ttyS1" || true

# Attach Bluetooth HCI UART
sleep .50
if ! hciattach -s 1500000 /dev/ttyS1 any 1500000 flow nosleep > /dev/null 2>&1; then
	echo "Failed to attach HCI device" >&2
	exit 1
fi
rfkill unblock all

exit 0
