# Pi 5 / CM5 onboard Wi-Fi (brcmfmac). Without a regulatory domain the driver scans
# disallowed channels and spams: brcmf_set_channel: set chanspec … fail, reason -52
# (open raspberrypi/linux#6049). Wi-Fi often still works; logs and scans are noisy.
{ pkgs, ... }:
let
  wifiCountry = "CA"; # change if you are not in Canada
in
{
  boot.kernelParams = [
    "cfg80211.ieee80211_regdom=${wifiCountry}"
  ];

  # Firmware country code (config.txt) — picked up before userspace regdom.
  hardware.raspberry-pi.extra-config = ''
    country=${wifiCountry}
  '';

  # Apply regdom before NetworkManager starts scanning.
  systemd.services.wifi-regulatory-domain = {
    description = "Set Wi-Fi regulatory domain for brcmfmac";
    wantedBy = [ "multi-user.target" ];
    before = [ "NetworkManager.service" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
    };
    script = ''
      ${pkgs.iw}/bin/iw reg set ${wifiCountry}
    '';
  };

  networking.networkmanager.wifi.powersave = false;
  networking.networkmanager.wifi.scanRandMacAddress = false;
  networking.networkmanager.connectionConfig."wifi.bgscan" = "0";
}
