{
  pkgs,
  lib,
  config,
  ...
}:
let
  allowManageGroups = [
    "root"
    "wheel"
    "lpadmin"
  ];
  polkitAllowGroups = builtins.concatStringsSep "||" (
    builtins.map (group: ''subject.isInGroup("${group}")'') allowManageGroups
  );

  printerMember = lib.map (user: user.name) (
    lib.attrsets.attrsToList (
      lib.attrsets.filterAttrs (name: value: value.isNormalUser) config.users.users
    )
  );

in
{
  environment.systemPackages = [ pkgs.simple-scan ];
  nixpkgs.config.allowUnfreePredicate =
    pkg:
    builtins.elem (lib.getName pkg) [
      "brgenml1lpr"
      "cups-brother-dcpt310"
      "cups-brother-dcpt720dw"
      "cups-brother-dcpt725dw"
    ];
  # nixpkgs.config.allowUnfree = true;
  services.ipp-usb.enable = true;
  services.printing = {
    enable = true;
    drivers = [
      pkgs.brlaser
      pkgs.gutenprint
      pkgs.brgenml1lpr
      pkgs.brgenml1cupswrapper
      pkgs.cups-brother-dcpt310
      pkgs.cups-brother-dcpt720dw
      pkgs.cups-brother-dcpt725dw
    ];

    extraFilesConf = ''
      SystemGroup ${builtins.concatStringsSep " " allowManageGroups}
    '';
  };

  security.polkit = {
    enable = true;

    extraConfig = ''
      polkit.addRule(function(action, subject) {
        var actionMatchs = (
          action.id.indexOf('org.opensuse.cupspkhelper.mechanism.') === 0
        );
        if (actionMatchs) {
          if (${polkitAllowGroups}) {
            return polkit.Result.YES
          }
        }
      });
    '';
  };

  hardware.sane = {
    enable = true;
  };

  users.groups.lpadmin.members = printerMember;
  users.groups.lp.members = printerMember;
  users.groups.scanner.members = printerMember;

}
