{ config, lib, ... }:
let
  cfg = config.khscodes.infrastructure.mailserver;
in
{
  config = lib.mkIf cfg.enable {
    khscodes.infrastructure.vault-server-approle.policy = {
      # TODO: Make this configurable
      "mx.kaareskovgaard.net/data/logins/admin" = {
        capabilities = [ "read" ];
      };
    };
    khscodes.services.vault-agent.templates = [
      {
        contents = ''
          {{- with secret "mx.kaareskovgaard.net/data/logins/admin" -}}
          {{ .Data.data.hashed_password }}
          {{- end -}}
        '';
        destination = "/run/secret/stalwart/users/admin";
        owner = "stalwart-mail";
        group = "stalwart-mail";
        restartUnits = [ "stalwart-mail.service" ];
      }
    ];
    systemd.services.stalwart-mail = {
      unitConfig.ConditionPathExists = [ "/run/secret/stalwart/users/admin" ];
      serviceConfig.ReadOnlyPaths = [ "/run/secret/stalwart/users/admin" ];
    };
    services.stalwart-mail = {
      settings = {
        authentication.fallback-admin = {
          user = "admin";
          secret = "%{file:/run/secret/stalwart/users/admin}%";
        };
      };
    };
    khscodes.infrastructure.provisioning.pre.modules = [
      {
        terraform.required_providers.random = {
          source = "hashicorp/random";
          version = "3.7.2";
        };
        provider.random = { };

        resource.random_password.stalwart_fallback_admin_password = {
          length = 48;
          numeric = true;
          lower = true;
          upper = true;
          special = false;
        };

        resource.vault_kv_secret_v2.stalwart_fallback_admin_password = {
          mount = "mx.kaareskovgaard.net";
          name = "logins/admin";
          data_json = ''
            {
              "hashed_password": ''${ jsonencode(resource.random_password.stalwart_fallback_admin_password.bcrypt_hash) },
              "password": ''${ jsonencode(resource.random_password.stalwart_fallback_admin_password.result) }
            }
          '';
        };
      }
    ];
  };
}
