{ config, ... }:
let
  # matrix homeserver discovery
  matrix_domain = "matrix.${config.networking.domain}";
  serverConfig = {
    "m.server" = "${matrix_domain}:443";
  };
  clientConfig = {
    "m.homeserver" = {
      base_url = "https://${matrix_domain}";
      # server_name = config.networking.domain;
    };
    "org.matrix.msc3575.proxy" = {
      url = "https://${matrix_domain}";
    };
  };
in
{
  services.caddy = {
    virtualHosts."${config.networking.domain}".extraConfig = ''
      file_server browse
      root * /srv/web/${config.networking.domain}
      respond /.well-known/matrix/client ${builtins.toJSON clientConfig}
      respond /.well-known/matrix/server ${builtins.toJSON serverConfig}
    '';
  };
}
