{
  config,
  lib,
  ...
}: let
  inherit (lib.modules) mkIf;

  mailConfig = config.services.mailserver;
  acmeRoot = "/var/lib/acme/acme-challenge";
in {
  config = mkIf (mailConfig.enable && mailConfig.sslConfig.useACME) {
    services.nginx = {
      enable = true;
      virtualHosts."${mailConfig.fqdn}" = {
        serverName = mailConfig.fqdn;
        serverAliases = mailConfig.domains;
        forceSSL = true;
        enableACME = true;
        inherit acmeRoot;
      };
    };

    security.acme.certs."${mailConfig.fqdn}" = {
      reloadServices = ["postfix.service" "dovecot2.service"];
    };
  };
}
