{ config, lib, ... }:
let
  cfg = config.khscodes.services.fail2ban;
in
{
  options.khscodes.services.fail2ban = {
    enable = lib.mkEnableOption "Enables fail2ban service for the instance";
    actions = lib.mkOption {
      type = lib.types.listOf lib.types.path;
      description = "Extra actions to add to fail2ban";
      default = [ ];
    };
    filters = lib.mkOption {
      type = lib.types.listOf lib.types.path;
      description = "Extra filters to add to fail2ban";
      default = [ ];
    };
  };

  config = lib.mkIf cfg.enable {
    environment.etc =
      (lib.listToAttrs (
        lib.lists.map (a: {
          name = "fail2ban/action.d/${builtins.baseNameOf a}";
          value = {
            source = a;
          };
        }) cfg.actions
      ))
      // (lib.listToAttrs (
        lib.lists.map (f: {
          name = "fail2ban/filter.d/${builtins.baseNameOf f}";
          value = {
            source = f;
          };
        }) cfg.filters
      ));
    services.fail2ban = {
      enable = true;
      bantime = "1h";
      bantime-increment = {
        enable = true;
        multipliers = "1 2 4 8 16 32 64 128 256";
        maxtime = "168h"; # Do not ban for more than 1 week
        overalljails = true;
      };
    };
  };
}
