{ config, lib, pkgs, ... }:
{
  imports = [ ./nginx ];

  config = lib.mkIf config.services.mailserver.enable {
    services = {
      radicale = {
        enable = true;
        settings.auth = {
          type = "htpasswd";
          htpasswd_filename = let
            mailAccounts = config.mailserver.loginAccounts;
            htpasswd = with lib; pkgs.writeText "radicale.users" (concatStrings
              (flip mapAttrsToList mailAccounts (mail: user:
                mail + ":" + user.hashedPassword + "\n"
              ))
            );
          in "${htpasswd}";
          htpasswd_encryption = "bcrypt";
        };
      };
      cloudflare-dyndns.domains = [ "cal.nixfox.ca" ];
    };

    environment.persistence."/persist".directories = [ "/var/lib/radicale" ];
  };
}
