#!/bin/sh
#===============================================================================
#
#  Copyright (C) 2025,2026, 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
HCI_IFACE="hci0"
MODULE_NAME="hci_uart"

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
}

set_btaddr() {
	hciconfig ${HCI_IFACE} 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 ${HCI_IFACE} cmd 0x3f 0x0001 ${bt_addr}
	hciconfig ${HCI_IFACE} down
	sleep 0.2
	hciconfig ${HCI_IFACE} up
}

is_kernel_module_loaded() {
	lsmod | grep -qs -w "^${MODULE_NAME}"
}

bt_init() {
	# If module is already loaded, skip
	is_kernel_module_loaded && log info "kernel module already present, skipping" && return 1

	for i in $(seq ${RETRIES}); do
		# Load manually the kernel module
		modprobe "${MODULE_NAME}"
		sleep 1
		# Reconfigure the HCI interface with the expected MAC address
		is_kernel_module_loaded && set_btaddr && log info "Bluetooth activated" && return 0
		bt_stop

		if [ "$i" -lt "$RETRIES" ]; then
			log err "Cannot initialize Bluetooth, retrying..."
		fi
	done

	log err "Failed to initialize Bluetooth interface"
	return 1
}

bt_stop() {
	hciconfig ${HCI_IFACE} down
	# Unload HCI driver instance
	rmmod "${MODULE_NAME}"
	rmmod btbcm
	log info "Bluetooth disabled"
}

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