{ lib, config, ... }:
let
  cfg = config.khscodes.infrastructure.mailserver;
  secretFile = "/run/secret/dovecot/ldap";
in
{
  options.khscodes.infrastructure.mailserver = {
    ldap = {
      mount = lib.mkOption {
        type = lib.types.str;
      };
      path = lib.mkOption {
        type = lib.types.str;
      };
    };
  };

  config = lib.mkIf cfg.enable {
    services.stalwart-mail.settings = {
      config.local-keys = [
        "storage.ldap.*"
      ];
      storage = {
        directory = "ldap";
      };
      directory.ldap = {
        type = "ldap";
        url = "ldaps://login.kaareskovgaard.net";
        base-dn = "dc=login,dc=kaareskovgaard,dc=net";
        bind = {
          dn = "dn=token";
          secret = "%{env:STALWART_LDAP_SECRET}%";
          auth = {
            method = "lookup";
          };
        };
        filter = {
          name = "(&(class=account)(memberOf=mail_user)(uid=?))";
          email = "(&(class=account)(memberOf=mail_user)(mail=?))";
        };
        attributes = {
          name = "name";
          class = "class";
          description = "name";
          groups = "memberOf";
          email = "mail;primary";
          email-alias = "mail;alternative";
          quota = "diskQuota";
        };
      };
    };
    systemd.services = {
      stalwart-mail = {
        unitConfig = {
          ConditionPathExists = [ secretFile ];
        };
        serviceConfig = {
          EnvironmentFile = secretFile;
        };
      };
    };

    khscodes.services.vault-agent.templates = [
      {
        contents = ''
          {{- with secret "${cfg.ldap.mount}/data/${cfg.ldap.path}" -}}
          STALWART_LDAP_SECRET={{ .Data.data.apiToken }}
          {{- end -}}
        '';
        destination = secretFile;
        owner = "stalwart-mail";
        group = "stalwart-mail";
        restartUnits = [
          "stalwart-mail.service"
        ];
      }
    ];
    # TODO: Include a similiar rule for openstack
    khscodes.infrastructure.hetzner-instance.extraFirewallRules = [
      {
        direction = "out";
        protocol = "tcp";
        port = 636;
        destination_ips = [
          "0.0.0.0/0"
          "::/0"
        ];
        description = "ldaps";
      }
    ];
    khscodes.infrastructure.vault-server-approle.policy = {
      "${cfg.ldap.mount}/data/${cfg.ldap.path}" = {
        capabilities = [ "read" ];
      };
    };
  };
}
