{ pkgs, lib, config, ... }:
let
  inherit (builtins) readFile;
  inherit (config.services) dovecot2;
  stateDir = "/var/lib/dovecot";
  domain = "sourcephile.fr";
  domainGroup = "sourcephile";
in
{
services.dovecot2.extraConfig =
  let domainConfig = ''
    ssl_cert = </var/lib/acme/${domain}/fullchain.pem
    ssl_key = </var/lib/acme/${domain}/key.pem
  '';
  in lib.mkAfter ''
  local_name mail.${domain} {
    ${domainConfig}
  }
  local_name imap.${domain} {
    ${domainConfig}
  }
  passdb {
    username_filter = *@${domain}
    # Because auth_bind=yes and auth_bind_userdn are used,
    # this cannot prefetch any userdb_*.
    driver = ldap
    # The path to the ldap.conf must be unique,
    # otherwise dovecot caches the result from other passdb,
    # which may be wrong because of username_filter.
    args = ${pkgs.writeText "${domain}-ldap.conf" (readFile ./ldap.conf)}
    default_fields =
    override_fields =
    skip = authenticated
  }
'';
security.acme.certs."${domain}" = {
  postRun = "systemctl reload dovecot2";
};
systemd.services.dovecot2 = {
  wants = [ "acme-selfsigned-${domain}.service" "acme-${domain}.service"];
  after = [ "acme-selfsigned-${domain}.service" ];
  preStart = ''
    install -D -d -m 1770 \
     -o "${dovecot2.user}" \
     -g "${domainGroup}" \
     ${stateDir}/home/${domain} \
     ${stateDir}/control/${domain} \
     ${stateDir}/index/${domain} \
     ${stateDir}/acl/${domain}

    # NOTE: do not set the sticky bit (+t)
    #       on acl/<domain>/, to let dovecot
    #       rename acl.db.lock (own by new user)
    #       to     acl.db      (own by old user)
    chmod -t ${stateDir}/acl/${domain}
  '';
};
services.nginx.virtualHosts."autoconfig.${domain}" = {
  serverName = "autoconfig.${domain}";
  #addSSL = true;
  extraConfig = ''
    access_log off;
    log_not_found off;
  '';
  forceSSL = true;
  useACMEHost = domain;
  root = ./autoconfig;
};
}