{ config, lib, ... }:
let
  cfg = config.khscodes.infrastructure.mailserver;
  oauthConfigFile = "/run/secret/dovecot/dovecot-oauth2.conf.ext";
in
{
  config = lib.mkIf cfg.enable {
    services.stalwart-mail.settings = {
      tracer.stdout.level = "trace";
      directory.oidc = {
        type = "oidc";
        url = "ldaps://login.kaareskovgaard.net";
        timeout = "1s";
        endpoint.url = "https://login.kaareskovgaard.net/oauth2/openid/dovecot/userinfo";
        endpoint.method = "userinfo";
        auth.method = "user-token";
        auth.username = "dovecot";
        auth.secret = "%{file:${oauthConfigFile}}%";
        fields.email = "email";
        fields.username = "preferred_username";
        fields.full-name = "name";
      };
    };
    khscodes.services.vault-agent.templates = [
      {
        contents = ''
          {{- with secret "kanidm/data/apps/dovecot" -}}
          {{ .Data.data.basic_secret }}@login.kaareskovgaard.net/oauth2/token/introspect
          {{- end -}}
        '';
        destination = oauthConfigFile;
        perms = "0600";
        owner = "stalwart-mail";
        group = "stalwart-mail";
        restartUnits = [ "stalwart-mail.service" ];
      }
    ];
    systemd.services.stalwart-mail = {
      serviceConfig.ReadOnlyPaths = [
        oauthConfigFile
      ];
      unitConfig.ConditionPathExists = [
        oauthConfigFile
      ];
    };
  };
}
