#!/usr/bin/bash

# Fix Bluetooth on Fedora (tested on Fedora 43+)
# Run with: sudo ./fix_bluetooth.sh

set -euo pipefail

if [[ $EUID -ne 0 ]]; then
    echo "Run this script with sudo: sudo ./fix_bluetooth.sh"
    exit 1
fi

REAL_USER="${SUDO_USER:-$USER}"

echo "=== Fixing Bluetooth on Fedora ==="

# Install required Bluetooth packages
echo "[1/6] Installing Bluetooth packages..."
dnf install -y bluez bluez-tools pipewire-codec-aptx

# Unblock Bluetooth if soft-blocked
echo "[2/6] Checking rfkill..."
if rfkill list bluetooth | grep -q "Soft blocked: yes"; then
    rfkill unblock bluetooth
    echo "  Unblocked Bluetooth."
else
    echo "  Not blocked."
fi

# Load btusb kernel module
echo "[3/6] Loading kernel module..."
if ! lsmod | grep -q "^btusb"; then
    modprobe btusb
    echo "  Loaded btusb."
else
    echo "  btusb already loaded."
fi

# Enable and restart bluetooth service
echo "[4/6] Restarting bluetooth service..."
systemctl enable --now bluetooth
systemctl restart bluetooth

# Power on the adapter (give the service a moment to initialize)
echo "[5/6] Powering on adapter..."
sleep 2
bluetoothctl power on

# Restart PipeWire for the real user (needs their D-Bus session)
echo "[6/6] Restarting PipeWire..."
USER_UID=$(id -u "$REAL_USER")
if [[ -S "/run/user/$USER_UID/bus" ]]; then
    sudo -u "$REAL_USER" DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$USER_UID/bus" \
        systemctl --user restart pipewire pipewire-pulse wireplumber
    echo "  PipeWire restarted."
else
    echo "  No D-Bus session found for $REAL_USER — log in to a desktop session and re-run, or reboot."
fi

echo ""
echo "=== Status ==="
systemctl status bluetooth --no-pager -l
echo ""
bluetoothctl show | head -10
echo ""
echo "Done. Try pairing your device with: bluetoothctl"
