{ config, lib, pkgs, ... }:

with lib;

let

  cfg = config.system.custom.wifi;

in
{

  options.system.custom.wifi = {
    enable = mkEnableOption "enable wifi";
    system = mkOption {
      default = "wpa_supplicant";
      type = with types; enum [ "wpa_supplicant" "networkmanager" ];
    };
    configurationFile = mkOption {
      default = null;
      type = with types; nullOr path;
      description = ''
        the target of /etc/wpa_supplicant.conf
      '';
    };
    interfaces = mkOption {
      type = with types; listOf string;
      default = [ ];
      description = ''
        list of interfaces to take care of,
        if empty it will test all interfaces
      '';
    };
  };

  config = mkMerge [

    (mkIf (cfg.enable && cfg.system == "wpa_supplicant") {
      networking.wireless.enable = true;
      networking.wireless.interfaces = cfg.interfaces;
    })

    (mkIf (cfg.enable && cfg.system == "networkmanager") {
      networking.networkmanager.enable = true;
      networking.networkmanager.wifi.powersave = 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
      '';
    })

    (mkIf (cfg.enable && cfg.configurationFile != null) {
      environment.etc."wpa_supplicant.conf".source = cfg.configurationFile;
    })

    (mkIf cfg.enable {

      networking.dhcpcd.allowInterfaces = cfg.interfaces;

      networking.usePredictableInterfaceNames = true;

      hardware.enableRedistributableFirmware = true;

      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"
        '')

      ];
    })

  ];

}