#!/bin/bash
set -e

# This grants the node binary cap_net_raw privileges, so it can start/stop BLE advertising.
# Update: Cap node for raw + admin (admin needed on modern kernels for HCI mgmt cmds)
setcap cap_net_raw,cap_net_admin+eip "$(readlink -f "$(which node)")"

# Stop AND disable bluetoothd so the HCI raw socket isn't contended.
systemctl stop bluetooth 2>/dev/null || true
systemctl disable bluetooth 2>/dev/null || true

# Bring up hci0. Use hciconfig if present (legacy bluez tools), else btmgmt
# Note: modern bluez 5.x ships it as part of bluez itself, hciconfig is deprecated.
if command -v hciconfig >/dev/null 2>&1; then
    hciconfig hci0 up || true
elif command -v btmgmt >/dev/null 2>&1; then
    btmgmt power on || true
else
    rfkill unblock bluetooth 2>/dev/null || true
fi

exit 0
