#!/bin/sh
#===============================================================================
#
#  Copyright (C) 2024,2025 by Digi International Inc.
#  All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License version 2 as published by
#  the Free Software Foundation.
#
#
#  !Description: Initialize Bluetooth interface
#
#===============================================================================

SCRIPTNAME="$(basename ${0})"
RETRIES=3

log() {
	if type "systemd-cat" >/dev/null 2>/dev/null; then
		systemd-cat -p "${1}" -t "${SCRIPTNAME}" printf "%s" "${2}"
	else
		logger -p "${1}" -t "${SCRIPTNAME}" "${2}"
	fi
}

bt_power() {
	#CCMP2 BT_REG_EN GPIO PZ5
	gpioset gpiochip11 5="${1}"
}

set_btaddr() {
	hciconfig hci0 up
	sleep 0.2
	bt_addr=$(hexdump -v -e '1/1 "%02X "' /proc/device-tree/bluetooth/mac-address \
			| awk '{ for(i=NF; i>0; i--) printf "0x%s ", $i }' \
			| sed 's/ $//')
	hcitool -i hci0 cmd 0x3f 0x0001 ${bt_addr}
	hciconfig hci0 down
	sleep 0.2
	hciconfig hci0 up
}

bt_init() {
	for i in $(seq ${RETRIES}); do
		# Perform a power cycle
		bt_power 0
		sleep 0.5
		bt_power 1

		# Load Bluetooth firmware on device
		if MBT_TRANSPORT=/dev/ttySTM1 timeout 10 mbt download /lib/firmware/brcm/CYW55500A1_FCC.hcd; then
			# Attach serial UART to the Bluetooth stack
			btattach -B /dev/ttySTM1 -P bcm -S 921600 &
			sleep 2

			# Reconfigure the HCI interface with the expected MAC address
			set_btaddr && log info "OK" && return 0
		fi
		log err "FAILED to bring hci0 up, retrying..."
		killall btattach 2> /dev/null
	done

	log err "FAILED (hci0 up)"
	return 1
}

bt_stop() {
	killall btattach
	bt_power 0
}

case "$1" in
	start)
		bt_init
		;;
	stop)
		bt_stop
		;;
	restart)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac
