{pkgs, lib, config, ...}:
let inherit (builtins) attrNames;
    inherit (config.services) dovecot2;
in
{
config = {
  services.nginx = {
    virtualHosts."autoconfig" =
    let servers = lib.concatMapStringsSep " "
                   (dom: "autoconfig.${dom}")
                   (attrNames dovecot2.domains);
    in
    {
      serverName = "autoconfig.${config.networking.domain}";
      serverAliases =
        map (domainAlias: "autoconfig." + domainAlias)
            config.networking.domainAliases;
      #addSSL = true;
      extraConfig = ''
        access_log off;
        log_not_found off;
      '';
      root = pkgs.writeTextFile {
        name = "autoconfig";
        destination = "/mail/config-v1.1.xml";
        text = ''
          <?xml version="1.0"?>
          <clientConfig version="1.1">
            <emailProvider id="%EMAILDOMAIN%">
              <!-- <displayName></displayName> -->
              <!-- <displayShortName></displayShortName> -->
              <domain>%EMAILDOMAIN%</domain>
              <incomingServer type="imap">
                <hostname>mail.%EMAILDOMAIN%</hostname>
                <port>993</port>
                <socketType>SSL</socketType>
                <username>%EMAILADDRESS%</username>
                <authentication>password-cleartext</authentication>
              </incomingServer>
              <incomingServer type="pop3">
                <hostname>mail.%EMAILDOMAIN%</hostname>
                <port>995</port>
                <socketType>SSL</socketType>
                <username>%EMAILADDRESS%</username>
                <authentication>password-cleartext</authentication>
                <pop3>
                  <leaveMessagesOnServer>false</leaveMessagesOnServer>
                  <downloadOnBiff>true</downloadOnBiff>
                </pop3>
              </incomingServer>
              <outgoingServer type="smtp">
                <hostname>mail.%EMAILDOMAIN%</hostname>
                <port>465</port>
                <socketType>SSL</socketType> <!-- see above -->
                <username>%EMAILADDRESS%</username> <!-- if smtp-auth -->
                <authentication>password-cleartext</authentication>
                <!-- <restriction>client-IP-address</restriction> -->
                <addThisServer>true</addThisServer>
                <useGlobalPreferredServer>false</useGlobalPreferredServer>
              </outgoingServer>
            </emailProvider>
            <!-- <clientConfigUpdate url="https://www.example.com/config/mozilla.xml" /> -->
          </clientConfig>
        '';
      };
    };
  };
};
}