{ lib, config, ... }:
let
  cfg = config.khscodes.infrastructure.mailserver;
  fqdn = config.khscodes.networking.fqdn;
  acmeDir = config.security.acme.certs.${fqdn}.directory;
  # extraDomainNames = lib.lists.filter (d: d != fqdn) (lib.lists.map (d: "mx.${d}") cfg.domains);
  extraDomainNames = [ ];
  user = "stalwart-mail";
in
{
  config = lib.mkIf cfg.enable {
    khscodes.services.nginx.virtualHosts."${fqdn}" = {
      locations."/" = {
        proxyPass = "http://127.0.0.1:8080";
        proxyWebsockets = true;
        recommendedProxySettings = true;
      };
    };
    services.stalwart-mail.settings = {
      certificate.default = {
        cert = "%{file:${acmeDir}/fullchain.pem}%";
        default = true;
        private-key = "%{file:${config.security.acme.certs.${fqdn}.directory}/key.pem}%";
      };
    };
    security.acme.certs.${fqdn} = {
      inherit extraDomainNames;
      postRun = ''
        systemctl restart stalwart-mail.service
      '';
    };
    systemd.services.stalwart-mail = {
      after = [ "acme-selfsigned-${fqdn}.service" ];
      wants = [ "acme-finished-${fqdn}.service" ];
      serviceConfig.ReadOnlyPaths = [ acmeDir ];
    };
    users.users.${user}.extraGroups = [
      config.security.acme.certs.${fqdn}.group
    ];
  };
}
