#!/bin/bash
# Fix MacBook10,1 suspend/resume WiFi issues caused by BCM4350 brcmfmac PCIe D3 timeout
#
# ROOT CAUSE: systemd-sleep hooks run AFTER kernel PM tries to freeze devices.
# brcmfmac driver is still loaded when kernel calls pci_pm_suspend() -> D3 timeout
# error -5 -> suspend fails -> retry -> firmware corruption -> WiFi dead.
#
# SOLUTION: Use systemd services (Before=sleep.target / After=suspend.target)
# which execute BEFORE kernel PM freezes and AFTER kernel PM resumes.
#
# Run with: sudo bash ~/fix-macbook12-suspend.sh
set -euo pipefail
if [[ $EUID -ne 0 ]]; then
echo "ERROR: Please run with sudo: sudo bash $0"
exit 1
fi
echo "=== 1/6 Removing old systemd-sleep hook ==="
if [[ -f /etc/systemd/system-sleep/brcmfmac-suspend.sh ]]; then
rm /etc/systemd/system-sleep/brcmfmac-suspend.sh
echo "Removed old hook"
else
echo "Old hook not found, skipping"
fi
cat > /etc/udev/rules.d/99-brcmfmac-typec.rules << 'UDEV'
# Reset brcmfmac when Type-C port state changes and WiFi is broken
ACTION=="change|remove", SUBSYSTEM=="typec", RUN+="/usr/local/bin/brcmfmac-typec-check.sh"
UDEV
cat > /usr/local/bin/brcmfmac-typec-check.sh << 'CHECK'
#!/bin/bash
# Only reset if WiFi is actually broken
if ip link show wlan0 &>/dev/null && iw dev wlan0 info &>/dev/null 2>&1; then
exit 0
fi
/usr/local/bin/brcmfmac-recovery.sh typec-hotplug
CHECK