{
  config,
  lib,
  pkgs,
  ...
}:
let
  fqdn = config.khscodes.networking.fqdn;
  cfg = config.khscodes.infrastructure.mailserver;
  # Increment this if ever changing mta-sts settings.
  policyVersion = 2;
  mtaStsWellKnown = pkgs.writeTextFile {
    name = "mta-sts.txt";
    text = ''
      version: STSv1
      mode: enforce
      max_age: 600
      mx: ${fqdn}
    '';
  };
in
{
  config = lib.mkIf cfg.enable {
    khscodes.services.nginx.virtualHosts = (
      lib.listToAttrs (
        lib.lists.map (domain: {
          name = "mta-sts.${domain}";
          value = {
            locations."=/.well-known/mta-sts.txt" = {
              alias = mtaStsWellKnown;
            };
            locations."/" = {
              return = 404;
            };
          };
        }) cfg.domains
      )
    );
    khscodes.infrastructure.provisioning.pre.modules = [
      {
        khscodes.cloudflare.dns.txtRecords = (
          lib.lists.map (domain: {
            fqdn = "_mta-sts.${domain}";
            content = ''"v=STSv1; id=${builtins.toString policyVersion}"'';
          }) cfg.domains
        );
        khscodes.cloudflare.dns.cnameRecords = (
          lib.lists.map (domain: {
            fqdn = "mta-sts.${domain}";
            content = fqdn;
            ttl = 600;
          }) cfg.domains
        );
      }
    ];
  };
}
