{ config, lib, ... }:
let
  floatingIPv4 = "78.47.245.200";
in
{
  systemd.network.networks."30-wan".addresses = [
    {
      Address = "${floatingIPv4}/32";
    }
    {
      Address = "2a01:4f8:c012:976d::/64";
    }
  ];

  services.fail2ban.jails = {
    # max 6 failures in 600 seconds
    "nginx-spam" = ''
      enabled  = true
      filter   = nginx-bruteforce
      logpath = /var/log/nginx/access.log
      backend = auto
      maxretry = 6
      findtime = 600
    '';

    # max 3 failures in 600 seconds
    "postfix-bruteforce" = ''
      enabled = true
      filter = postfix-bruteforce
      findtime = 600
      maxretry = 3
    '';
  };

  mailserver = {
    enable = true;
    fqdn = "mail.escapeangle.com";
    domains = [
      "escapeangle.com"
      "kinkystar.com"
    ];

    loginAccounts = {
      "lander@escapeangle.com" = {
        hashedPasswordFile = config.sops.secrets.mail-password-lander.path;

        aliases = [
          "postmaster@escapeangle.com"
        ];

        catchAll = [
          "escapeangle.com"
        ];
      };

      "authelia@escapeangle.com" = {
        hashedPasswordFile = config.sops.secrets.mail-password-authelia.path;
      };

      "forgejo@escapeangle.com" = {
        hashedPasswordFile = config.sops.secrets.mail-password-forgejo.path;
      };

      "bitwarden@kinkystar.com" = {
        hashedPasswordFile = config.sops.secrets.mail-password-kinkystar-bitwarden.path;
        sendOnly = true;
      };

      "docuseal@kinkystar.com" = {
        hashedPasswordFile = config.sops.secrets.mail-password-kinkystar-docuseal.path;
        sendOnly = true;
      };
    };

    extraVirtualAliases = {
      "abuse@escapeangle.com" = "lander@escapeangle.com";
    };

    certificateScheme = "acme-nginx";

    enableImap = true;
    enableImapSsl = true;

    enableManageSieve = true;

    virusScanning = true;
  };

  services.postfix = {
    config = {
      inet_protocols = "ipv4";
      smtp_bind_address = floatingIPv4;

      virtual_mailbox_domains = lib.mkForce (builtins.toFile "vhosts" "escapeangle.com");
    };

    localRecipients = [ "@escapeangle.com" ];
  };

  sops = {
    defaultSopsFile = ./mail-01.yaml;
    validateSopsFiles = false;

    secrets = {
      mail-password-lander = {
        owner = "root";
        group = "root";
      };

      mail-password-authelia = {
        owner = "root";
        group = "root";
      };

      mail-password-forgejo = {
        owner = "root";
        group = "root";
      };

      mail-password-kinkystar-bitwarden = {
        owner = "root";
        group = "root";
      };

      mail-password-kinkystar-docuseal = {
        owner = "root";
        group = "root";
      };
    };
  };

  system.stateVersion = "24.11";
}
