{
  config,
  pkgs,
  lib,
  ...
}: let
  inherit (lib.modules) mkIf;
  inherit (lib.strings) concatStringsSep;
  inherit (lib.attrsets) mapAttrsToList;

  mailConfig = config.services.mailserver;

  inherit (mailConfig) vmail;
  vmailUser = vmail.user;
  vmailGroup = vmail.group;

  inherit (mailConfig) sieveDirectory;

  scriptForUser = name: config:
    if builtins.isString config.sieveScript
    then ''
      cat ${builtins.toFile "default.sieve" config.sieveScript} > "${sieveDirectory}/${name}/default.sieve"
      chown "${vmailUser}:${vmailGroup}" "${sieveDirectory}/${name}/default.sieve"
    ''
    else ''
      if [ -f "${sieveDirectory}/${name}/default.sieve" ]; then
        rm "${sieveDirectory}/${name}/default.sieve"
      fi
      if [ -f "${sieveDirectory}/${name}.svbin" ]; then
        rm "${sieveDirectory}/${name}/default.svbin"
      fi
    '';

  virtualMailUsersActivationScript = pkgs.writeScript "activate-virtual-mail-users" ''
    #!${pkgs.stdenv.shell}

    set -euo pipefail

    ${concatStringsSep "\n" (mapAttrsToList (name: config: scriptForUser name config) mailConfig.accounts)}
  '';
in {
  config = mkIf mailConfig.enable {
    users.users."${vmailUser}" = {
      isSystemUser = true;

      home = vmail.directory;
      createHome = true;

      uid = vmail.userID;
      group = "${vmailGroup}";
    };

    users.groups."${vmailGroup}" = {
      gid = vmail.groupID;
    };

    systemd.tmpfiles.rules =
      [
        "d '${sieveDirectory}' - ${vmailUser} ${vmailGroup} - -"
      ]
      ++ (map (
        email: "d '${sieveDirectory}/${email}' 770 ${vmailUser} ${vmailGroup} - -"
      ) (builtins.attrNames mailConfig.accounts));

    systemd.services.activate-virtual-mail-users = {
      wantedBy = ["multi-user.target"];
      before = ["dovecot2.service"];
      serviceConfig.ExecStart = virtualMailUsersActivationScript;
      enable = true;
    };
  };
}
