{ outputs, config, lib, pkgs, ... }:
with lib;
let
  cfg = config.nas-apps.crowdsec;
in
{
  imports = [ ./options.nix ];
  config = lib.mkIf cfg.enable {
    services = {
      crowdsec = let
        yaml = (pkgs.formats.yaml {}).generate;
        acquisitions_file = yaml "acquisitions.yaml" {
          source = "journalctl";
          journalctl_filter = ["_SYSTEMD_UNIT=sshd.service"];
          labels.type = "syslog";
        };
      in  {
        enable = true;
        enrollKeyFile = "${cfg.dataDir}/enroll.key";
        settings = {
          crowdsec_service.acquisition_path = acquisitions_file;
          api.server = {
            listen_uri = "0.0.0.0:${toString cfg.port}";
          };
        };
      };

      crowdsec-firewall-bouncer = {
        enable = true;
        settings = {
          api_key = cfg.apiKey;
          api_url = "http://${cfg.apiAddress}:${toString cfg.port}";
        };
      };
    };

    systemd.services.crowdsec.serviceConfig = {
      ExecStartPre = let
        script = pkgs.writeScriptBin "register-bouncer" ''
          #!${pkgs.runtimeShell}
          set -eu
          set -o pipefail

          if ! cscli bouncers list | grep -q "nas-bouncer"; then
            cscli bouncers add "nas-bouncer" --key "${cfg.apiKey}"
          fi
        '';
      in ["${script}/bin/register-bouncer"];
    };

    networking = {
      firewall = {
        allowedTCPPorts = [ cfg.port ];
        allowedUDPPorts = [ cfg.port ];
      };
    };
  };
}