{config, ...}: let
  # Tuwunel uses a list for ports
  tuwunel-port = config.m3ta.ports.get "tuwunel";
in {
  services.matrix-tuwunel = {
    enable = true;
    settings.global = {
      server_name = "m3ta.dev";
      address = ["127.0.0.1"];
      port = [tuwunel-port];
      max_request_size = 20000000;
      allow_registration = true;
      registration_token_file = config.age.secrets."tuwunel-registration-token".path;
      allow_encryption = true;
      allow_federation = true;
      trusted_servers = ["matrix.org"];
    };
  };

  # Traefik configuration for Tuwunel
  services.traefik.dynamicConfigOptions.http = {
    services.tuwunel.loadBalancer.servers = [
      {
        url = "http://localhost:${toString tuwunel-port}/";
      }
    ];

    routers.tuwunel = {
      rule = "Host(`matrix.m3ta.dev`)";
      tls = {
        certResolver = "godaddy";
      };
      service = "tuwunel";
      entrypoints = "websecure";
    };

    # Federation endpoint on base domain
    routers.tuwunel-federation = {
      rule = "Host(`m3ta.dev`) && PathPrefix(`/_matrix`)";
      tls = {
        certResolver = "godaddy";
      };
      service = "tuwunel";
      entrypoints = "websecure";
    };
  };

  # Open federation port
  networking.firewall.allowedTCPPorts = [8448];
}
