#! /bin/bash
#
# vim: ts=2:sw=2:set ai:syn on:
#
# requires bash 4+
#

map_firmware(){
	local -A firmware=(
		['0a5c:21d3']="/lib/firmware/bcm20702a1/BCM43142A0_001.001.011.0084.0086.hcd"
		['0a5c:21e6']="/lib/firmware/bcm20702a1/BCM20702A1_001.002.014.0449.0462.hcd"
		['0a5c:21f3']="/lib/firmware/bcm20702a1/BCM20702A1_001.002.014.0449.0461.hcd"
		['0a5c:21f4']="/lib/firmware/bcm20702a1/BCM20702A1_001.002.014.0449.0455.hcd"
		['413c:8197']="/lib/firmware/bcm20702a1/BCM20702A1_001.002.014.0449.0672.hcd"
	)
	echo ${firmware[$1]}
}

flash_device(){
	${BRCM_PATCHRAM_PLUS} --patchram $1 $2
}

scan_usb_devices(){
	local hci_interface=$1
	for usbid in $(lsusb | (while read d d d d d id d; do echo $id; done)); do
		fw=$(map_firmware $usbid)
		if [ "x$fw" != "x" ]; then
			flash_device $fw $hci_interface
		fi
	done
}

TRIES=5
RETRY_DELAY=1	# Wait 1 second between hci device search.
BRCM_PATCHRAM_PLUS=/usr/bin/brcm_patchram_plus_usb
HCITOOL=/usr/bin/hcitool
LOGGER=echo

#
# Find an HCI device and flash it.
#
# I'd like to be able to correlate a USB id with an HCI device but until
# then, we simply flash the first bluetooth device we find and exit.
#
for ((x = 1; x <= ${TRIES}; x++)); do
	if ${HCITOOL} dev | grep -q 'hci[0-9]'; then
		DEV=$(${HCITOOL} dev | grep 'hci[0-9]' | head -1 | (read dev x; echo $dev))
		${LOGGER} "Found hci device $DEV in $x tries."
		scan_usb_devices $DEV
		exit
	fi
	sleep ${RETRY_DELAY}
done
