{ config, lib, ... }:
let
  sec = config.sops.secrets;
  inherit (config.machine.mail)
    enable
    domain
    fqdn
    ;
in
{
  imports = [
    (builtins.fetchTarball {
      url = "https://gitlab.com/simple-nixos-mailserver/nixos-mailserver/-/archive/main/nixos-mailserver-main.tar.gz";
      sha256 = "1wk7fsmabngy98596rkpf6pxxajpkz2g25cimwzx3brr4bc2ck0l";
    })
  ];

  mailserver = {
    inherit enable;
    inherit fqdn;
    stateVersion = 5;
    domains = [ domain ];
    messageSizeLimit = 52428800; # 50MB
    enableManageSieve = true;

    localDnsResolver = false;

    accounts = {
      "admin@${domain}" = {
        hashedPasswordFile = sec."mail/serviceHashedPassword".path;
        aliases = [
          "postmaster@${domain}"
          "system@${domain}"
          "contact@${domain}"
          "sales@${domain}"
        ];
      };
      "rus07tam@${domain}" = {
        hashedPasswordFile = sec."rus07tam/hashedPassword".path;
        aliases = [ ];
      };
      "nikitahapanulstaff228@${domain}" = {
        hashedPasswordFile = sec."mail/NikitaHapanulStaff228HashedPassword".path;
        aliases = [
          "mamutraxal@${domain}"
          "sava.uwu@${domain}"
        ];
      };
      "nikitapocox6prohype@${domain}" = {
        hashedPasswordFile = sec."mail/nikitapocox6prohype".path;
        aliases = [
          "pomoemuhype@${domain}"
          "nikita.uwu@${domain}"
        ];
      };
      "openclaw@${domain}" = {
        hashedPasswordFile = sec."mail/openclawHashedPassword".path;
        aliases = [ "nexor@${domain}" ];
      };
    };

    x509.useACMEHost = config.mailserver.fqdn;

    dkim = {
      enable = true;
      keyDirectory = "/var/dkim";
      defaults.selector = "default";
    };
  };
}
