{ config
, lib
, ...
}:
with lib;
with lib.metacfg;
let
  cfg = config.metacfg.system.limits;
in
{
  options.metacfg.system.limits = with types; {
    enable = mkBoolOpt false "Whether or not to enable system limits configuration.";
    nofileLimit = mkOption {
      type = types.int;
      default = 32768;
      description = "Maximum number of open file descriptors per process.";
    };
    memlockLimit = mkOption {
      type = types.int;
      default = 32768;
      description = "Maximum locked-in-memory address space.";
    };
  };

  config = mkIf cfg.enable {
    systemd.user.extraConfig = "DefaultLimitNOFILE=${toString cfg.nofileLimit}";

    security.pam.loginLimits = [
      {
        domain = "*";
        item = "nofile";
        type = "-";
        value = toString cfg.nofileLimit;
      }
      {
        domain = "*";
        item = "memlock";
        type = "-";
        value = toString cfg.memlockLimit;
      }
    ];
  };
}