{ config, lib, pkgs, ... }:
with lib;
with types;
{

  options.components.network.wifi.enable = mkOption {
    type = bool;
    default = config.components.network.enable;
  };

  config = mkIf config.components.network.wifi.enable {

    networking.usePredictableInterfaceNames = true;

    networking.networkmanager.enable = true;
    networking.networkmanager.wifi.powersave = lib.mkDefault true;
    networking.networkmanager.extraConfig = ''
      # The number of times a connection activation should be automatically tried
      # before switching to another one. This value applies only to connections
      # that can auto-connect and have a connection. autoconnect-retries property set to -1.
      # If not specified, connections will be tried 4 times.
      # Setting this value to 1 means to try activation once, without retry.
      autoconnect-retries-default=999
    '';


    hardware.enableRedistributableFirmware = true;

    # because Networkd-wait-online is just failing.
    systemd.services.systemd-networkd-wait-online.enable = false;
    systemd.services.NetworkManager-wait-online.enable = false;

    environment.systemPackages = [

      (pkgs.writeShellScriptBin "scan-wifi" ''
        # todo : use column to make a nice view
        ${pkgs.wirelesstools}/bin/iwlist scan | \
          grep -v "Interface doesn't support scanning" | \
          sed -e '/^\s*$/d' | \
          grep -e "ESSID" -e "Encrypt" | \
          sed -e "s/Encryption key:on/encrypted/g" | \
          sed -e "s/Encryption key:off/open/g" | \
          sed -e "s/ESSID://g" | \
          xargs -L 2 printf "%9s - '%s'\n"
      '')

    ];
  };

}