Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions bin/omarchy-restart-bluetooth
Original file line number Diff line number Diff line change
@@ -1,7 +1,85 @@
#!/bin/bash

# omarchy:summary=Unblock and restart the bluetooth service.
# omarchy:requires-sudo=true

# bluetoothctl waits indefinitely for bluetoothd, so every probe needs its own
# guard. Keep it short: once the daemon is up the answer is immediate, and the
# guard only has to cover a daemon that went away between the checks.
controller_present() {
timeout 2s bluetoothctl list 2>/dev/null | grep -q '^Controller '
}

# Budget elapsed seconds rather than polls. A poll that spends its whole guard
# is exactly the case worth bounding, and counting iterations would stretch a
# five second window into half a minute.
wait_for_controller() {
local deadline=$(( SECONDS + $1 ))

while (( SECONDS < deadline )); do
controller_present && return 0
sleep 1
done

return 1
}

# Seconds to wait for a controller after the restart, and again after a btusb
# reload, which has a firmware upload to get through. Overridable so the shell
# tests can drive the escalation without spending the real budget.
restart_wait="${OMARCHY_BLUETOOTH_RESTART_WAIT:-5}"
reload_wait="${OMARCHY_BLUETOOTH_RELOAD_WAIT:-15}"

echo -e "Unblocking bluetooth...\n"
rfkill unblock bluetooth
rfkill list bluetooth

# Unconditional: a daemon that lost sync with D-Bus adapter state still lists
# its controller, so there is no reliable way to tell that case from a healthy
# one first. The restart is what the summary has always promised.
echo -e "\nRestarting bluetooth service...\n"

# A restart systemd began but could not finish has already stopped bluetoothd,
# so this cannot promise that nothing changed.
if ! sudo systemctl restart bluetooth.service; then
echo "Could not restart bluetooth.service. Check 'systemctl status bluetooth.service'." >&2
exit 1
fi

# The unit carries ConditionPathIsDirectory=/sys/class/bluetooth, so a machine
# with no Bluetooth stack passes the restart above without ever starting
# bluetoothd. Waiting for a controller would then burn the whole budget on a
# daemon that was never meant to run, and reloading btusb cannot help either.
if ! systemctl is-active --quiet bluetooth.service; then
echo "bluetooth.service is not running. Check 'systemctl status bluetooth.service'." >&2
exit 1
fi

# An adapter whose firmware handshake timed out stays in HCI_SETUP and is hidden
# from bluetoothd, and restarting the daemon cannot clear that. Reloading the USB
# driver re-runs the upload, which is the only way back without a reboot.
if ! wait_for_controller "$restart_wait" && lsmod | grep -q '^btusb'; then
echo -e "\nNo controller yet. Reloading btusb...\n"

# A failed unload leaves btusb loaded, so there is nothing to put back. Say so
# instead of reloading a driver that never came out.
if sudo modprobe -r btusb; then
sudo modprobe btusb || echo "Could not load btusb back after unloading it." >&2
else
echo "Could not unload btusb; the driver is still in use." >&2
fi

wait_for_controller "$reload_wait"
fi

echo -e "\nBluetooth status:\n"

# List once and print what was checked: a second call could hang, or come back
# empty, if bluetoothd went away in between.
if controllers=$(timeout 2s bluetoothctl list 2>/dev/null | grep '^Controller '); then
echo "$controllers"
else
echo "No Bluetooth controller is available."
echo "Check 'journalctl -b -k' for adapter firmware errors; bluetoothd's own log is 'journalctl -b -u bluetooth'."
exit 1
fi
171 changes: 171 additions & 0 deletions test/shell.d/restart-bluetooth-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
#!/bin/bash

set -euo pipefail

source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh"

tmp_dir=$(mktemp -d)
trap 'rm -rf "$tmp_dir"' EXIT

mkdir -p "$tmp_dir/bin"

cat >"$tmp_dir/bin/rfkill" <<'STUB'
#!/bin/bash
printf 'rfkill %s\n' "$*" >>"$STUB_CALLS"
STUB

cat >"$tmp_dir/bin/sudo" <<'STUB'
#!/bin/bash
printf 'sudo %s\n' "$*" >>"$STUB_CALLS"
[[ $STUB_SUDO_FAILS == "yes" ]] && exit 1
exec "$@"
STUB

cat >"$tmp_dir/bin/systemctl" <<'STUB'
#!/bin/bash
printf 'systemctl %s\n' "$*" >>"$STUB_CALLS"

if [[ $1 == "is-active" ]]; then
[[ $STUB_DAEMON_ACTIVE == "yes" ]] && exit 0
exit 3
fi

[[ $1 == "restart" && $STUB_CONTROLLER_AFTER == "restart" ]] && touch "$STUB_STATE/controller"
exit 0
STUB

cat >"$tmp_dir/bin/modprobe" <<'STUB'
#!/bin/bash
printf 'modprobe %s\n' "$*" >>"$STUB_CALLS"

# A busy module keeps btusb loaded, so the unload reports failure and the driver
# never leaves the kernel.
[[ $1 == "-r" && $STUB_UNLOAD_FAILS == "yes" ]] && exit 1

[[ $1 == "btusb" && $STUB_CONTROLLER_AFTER == "btusb" ]] && touch "$STUB_STATE/controller"
exit 0
STUB

cat >"$tmp_dir/bin/lsmod" <<'STUB'
#!/bin/bash
[[ $STUB_BTUSB_LOADED == "yes" ]] && echo "btusb 73728 0"
exit 0
STUB

cat >"$tmp_dir/bin/bluetoothctl" <<'STUB'
#!/bin/bash
printf 'bluetoothctl %s\n' "$*" >>"$STUB_CALLS"
if [[ $1 == "list" && -n ${STUB_LIST_ANSWERS:-} ]]; then
(( $(grep -c '^bluetoothctl list' "$STUB_CALLS") > STUB_LIST_ANSWERS )) && exec sleep 30
fi
if [[ $1 == "list" && -f $STUB_STATE/controller ]]; then
echo "Controller AA:BB:CC:DD:EE:FF omarchy [default]"
fi
exit 0
STUB
Comment on lines +55 to +65

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Stalled requests go untested

The new tests never make bluetoothctl stall or check elapsed time. Removing the probe timeout or changing the wait back to a fixed number of polls would still pass these cases, despite breaking the bounded-wait behavior. Add a stalled-command case with an outer timeout and an elapsed-time check.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!


chmod +x "$tmp_dir"/bin/*

# The waits are driven down to a second so the expiry paths stay cheap; the
# script's own defaults are what ship.
run_restart_bluetooth() {
STUB_STATE="$tmp_dir/state" \
STUB_CALLS="$tmp_dir/calls" \
STUB_CONTROLLER_AFTER="$1" \
STUB_BTUSB_LOADED="${2:-yes}" \
STUB_DAEMON_ACTIVE="${3:-yes}" \
STUB_SUDO_FAILS="${4:-no}" \
STUB_UNLOAD_FAILS="${5:-no}" \
OMARCHY_BLUETOOTH_RESTART_WAIT=1 \
OMARCHY_BLUETOOTH_RELOAD_WAIT=1 \
PATH="$tmp_dir/bin:$PATH" \
"$ROOT/bin/omarchy-restart-bluetooth"
}

reset_stubs() {
rm -rf "$tmp_dir/state"
mkdir -p "$tmp_dir/state"
: >"$tmp_dir/calls"
}

# The script's summary has always promised a restart, but it only ran rfkill:
# a desynced bluetoothd stayed desynced and the menu's recovery action was a
# no-op.
reset_stubs
run_restart_bluetooth restart >/dev/null
grep -qx 'rfkill unblock bluetooth' "$tmp_dir/calls" || fail "restart bluetooth unblocks the rfkill soft block"
pass "restart bluetooth unblocks the rfkill soft block"

grep -qx 'systemctl restart bluetooth.service' "$tmp_dir/calls" || fail "restart bluetooth restarts bluetooth.service"
pass "restart bluetooth restarts bluetooth.service"

grep -q '^modprobe' "$tmp_dir/calls" && fail "restart bluetooth leaves btusb alone once a controller answers"
pass "restart bluetooth leaves btusb alone once a controller answers"

# The status shows the listing that was checked. Listing again after the check
# hangs, or prints nothing and exits 0, if bluetoothd goes away in between: here
# it answers the wait's probe and the status check, then stops answering.
reset_stubs
started=$SECONDS
output=$(STUB_LIST_ANSWERS=2 run_restart_bluetooth restart 2>&1) || fail "restart bluetooth reports the controller it checked" "$output"
grep -q '^Controller ' <<<"$output" || fail "restart bluetooth prints the controller it checked" "$output"
(( SECONDS - started < 10 )) || fail "restart bluetooth does not list again after the check"
pass "restart bluetooth prints the controller it checked"

# A restart the user cancelled at the password prompt must not be reported as a
# recovery, however healthy the adapter already looked. The message is matched
# whole: its old second half claimed nothing had changed, which a restart that
# only got as far as stopping bluetoothd cannot promise.
reset_stubs
touch "$tmp_dir/state/controller"
output=$(run_restart_bluetooth restart yes yes yes 2>&1) && fail "restart bluetooth fails when the service restart fails"
grep -qxF "Could not restart bluetooth.service. Check 'systemctl status bluetooth.service'." <<<"$output" || fail "restart bluetooth explains a restart it could not run"
pass "restart bluetooth fails when the service restart fails"

# Same refusal with nothing listed, which is the only arrangement where the
# reload is otherwise reachable: escalating would ask again for the password it
# was just denied. Counting sudo is what catches that.
reset_stubs
run_restart_bluetooth never yes yes yes >/dev/null 2>&1 && fail "restart bluetooth stops before btusb when the restart failed"
sudo_calls=$(grep -c '^sudo ' "$tmp_dir/calls" || true)
(( sudo_calls == 1 )) || fail "restart bluetooth stops before btusb when the restart failed"
pass "restart bluetooth stops before btusb when the restart failed"

# bluetooth.service carries ConditionPathIsDirectory=/sys/class/bluetooth, so a
# machine with no stack takes a clean exit from the restart. Waiting on a daemon
# that was never started would spend the whole budget printing nothing.
reset_stubs
output=$(run_restart_bluetooth never yes no 2>&1) && fail "restart bluetooth fails when the daemon did not start"
grep -q 'bluetooth.service is not running' <<<"$output" || fail "restart bluetooth explains a daemon that did not start"
grep -q '^bluetoothctl' "$tmp_dir/calls" && fail "restart bluetooth does not poll for a controller without a daemon"
pass "restart bluetooth fails without polling when the daemon did not start"

# A firmware handshake that timed out leaves the controller in HCI_SETUP, hidden
# from bluetoothd. Only a driver reload re-runs the upload.
reset_stubs
run_restart_bluetooth btusb >/dev/null
grep -qx 'modprobe -r btusb' "$tmp_dir/calls" || fail "restart bluetooth reloads btusb when no controller answers"
grep -qx 'modprobe btusb' "$tmp_dir/calls" || fail "restart bluetooth loads btusb back after unloading it"
pass "restart bluetooth reloads btusb when no controller answers"

# An unload that fails leaves btusb loaded, so there is nothing to put back. The
# script has to say that rather than claim a reload it never performed.
reset_stubs
output=$(run_restart_bluetooth never yes yes no yes 2>&1) && true
grep -qx 'modprobe -r btusb' "$tmp_dir/calls" || fail "restart bluetooth attempts the unload"
grep -qx 'modprobe btusb' "$tmp_dir/calls" && fail "restart bluetooth does not load btusb after a failed unload"
grep -q 'Could not unload btusb' <<<"$output" || fail "restart bluetooth reports an unload it could not perform"
pass "restart bluetooth reports a failed unload instead of reloading"

# Nothing to reload on an adapter that is not a USB one.
reset_stubs
run_restart_bluetooth never no >/dev/null 2>&1 && fail "restart bluetooth reports a controller it never recovered"
grep -q '^modprobe' "$tmp_dir/calls" && fail "restart bluetooth only reloads btusb when btusb is loaded"
pass "restart bluetooth only reloads btusb when btusb is loaded"

# A dead adapter has to stay visibly dead; the menu action must not claim success.
reset_stubs
status_output=$(run_restart_bluetooth never 2>&1) && fail "restart bluetooth fails when no controller comes back"
grep -q 'No Bluetooth controller is available' <<<"$status_output" || fail "restart bluetooth explains an adapter that stayed wedged"
grep -q 'journalctl -b -k' <<<"$status_output" || fail "restart bluetooth points at the kernel log, where adapter firmware errors land"
pass "restart bluetooth fails when no controller comes back"