{ pkgs, lib, config, ... }:
let
  inherit (lib) types;
  inherit (config.services) postfix;
in
{
  options = {
    services.postfix = {
      tls_server_sni_maps = lib.mkOption {
        type = types.attrsOf (types.listOf types.path);
        default = { };
        apply = m: pkgs.writeText "sni" (lib.concatStringsSep "\n" (lib.mapAttrsToList
          (domain: x509: ''
            ${domain} ${lib.concatStringsSep " " x509}
          '')
          m));
      };
    };
  };
  config = {
    systemd.services.postfix = {
      preStart = ''
        install -m 400 -o root -g root ${postfix.tls_server_sni_maps} /run/postfix/postfix-sni
        ${pkgs.postfix}/bin/postmap -F hash:/run/postfix/postfix-sni
      '';
      serviceConfig = {
        RuntimeDirectory = [ "postfix" ];
      };
    };
    services.postfix = {
      masterConfig = {
        submissions-header-cleanup = {
          type = "unix";
          private = false;
          maxproc = 0;
          command = "cleanup";
          args = [
            "-o"
            ("header_checks=pcre:" + pkgs.writeText "submission_header_cleanup_rules" ''
              # Removes sensitive headers from mails handed in via the submission or smtps port.
              # See https://thomas-leister.de/mailserver-debian-stretch/
              # Uses "pcre" style regex.

              /^Received:/         IGNORE
              /^User-Agent:/       IGNORE
              /^X-Enigmail:/       IGNORE
              /^X-Mailer:/         IGNORE
              /^X-Originating-IP:/ IGNORE
            '')
          ];
        };
      };
    };
  };
}