#!/bin/bash
# Fix MT7921 WiFi slow connection and stability issues
# Run as root or with sudo

echo "Fixing MT7921 WiFi issues..."

# 1. Set power management to off (already done, but ensure it's persistent)
echo "Setting WiFi power management to off..."
for iface in $(iw dev | awk '/Interface/ {print $2}'); do
    iw dev "$iface" set power_save off
done

# 2. Create NetworkManager config to disable power saving
echo "Creating NetworkManager config..."
cat <<EOF | sudo tee /etc/NetworkManager/conf.d/wifi-powersave.conf
[connection]
wifi.powersave = 2
EOF

# 3. Add kernel parameters for MT7921 stability (systemd-boot)
echo "Adding kernel parameters for MT7921..."
if ! grep -q "pcie_aspm=off" /boot/loader/entries/arch.conf; then
    sudo sed -i 's/options.*/& pcie_aspm=off/' /boot/loader/entries/arch.conf
    echo "Added pcie_aspm=off to kernel parameters"
fi

# 4. Create udev rule to disable ASPM for MT7921
echo "Creating udev rule for MT7921..."
cat <<EOF | sudo tee /etc/udev/rules.d/99-mt7921-aspm.rules
# Disable ASPM for MT7921 WiFi cards
ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x14c3", ATTR{device}=="0x7961", ATTR{power/control}="on"
EOF

# 5. Set WiFi regulatory domain (if needed)
echo "Setting WiFi regulatory domain..."
if command -v iwreg &> /dev/null; then
    sudo iwreg set 00
else
    echo "iwreg not found, skipping regulatory domain setting"
fi

# 6. Reload services
echo "Reloading services..."
sudo systemctl reload NetworkManager
sudo udevadm control --reload-rules
sudo udevadm trigger

echo ""
echo "MT7921 WiFi fixes applied!"
echo ""
echo "To apply kernel parameter changes, you need to:"
echo "1. Reboot the system (systemd-boot automatically uses the updated config)"
echo ""
echo "If issues persist, try these additional steps:"
echo "- Check if your router supports WPA3, try WPA2 instead"
echo "- Try connecting to 2.4GHz instead of 5GHz"
echo "- Update your kernel to the latest version" 