{
  pkgs,
  config,
  ...
}: let
  fqdn = "${hostname}.${domain}";
  domain = "tristans.cloud";
  hostname = "matrix";
  mkWellKnown = data: ''
    default_type application/json;
    add_header Access-Control-Allow-Origin *;
    return 200 '${builtins.toJSON data}';
  '';
  port = 8008;
  inherit (config) sops;
  inherit (config.services) matrix-synapse matrix-sliding-sync;
  inherit (sops) secrets templates;
in {
  services.postgresql.enable = true;
  services.postgresql.initialScript = pkgs.writeText "synapse-init.sql" ''
    CREATE ROLE "matrix-synapse" WITH LOGIN PASSWORD 'synapse';
    CREATE DATABASE "matrix-synapse" WITH OWNER "matrix-synapse"
      TEMPLATE template0
      LC_COLLATE = "C"
      LC_CTYPE = "C";
  '';

  sops.secrets = {
    "synapse/signing_key".owner = "matrix-synapse";
    "synapse/oidc_client_secret" = {};
    "synapse/sliding_sync_secret" = {};
  };
  sops.templates = {
    "synapse/secrets.yaml" = {
      owner = "matrix-synapse";
      content = builtins.toJSON {
        oidc_providers = [
          {
            idp_id = "authentik";
            idp_name = "authentik";
            discover = true;
            issuer = "https://auth.tristans.cloud/application/o/chat/";
            client_id = "fdad520e8c57f228aaa658aa74d5e00ba9b164a3";
            client_secret = sops.placeholder."synapse/oidc_client_secret";
            scopes = ["openid" "profile" "email"];
            user_mapping_provider = {
              config = {
                localpart_template = "{{ user.preferred_username }}";
                display_name_template = "{{ user.name|capitalize }}";
              };
            };
          }
        ];
      };
    };
    "synapse/sliding_sync_env".content = ''
      SYNCV3_SECRET=${sops.placeholder."synapse/sliding_sync_secret"}
    '';
  };

  services.matrix-synapse = {
    enable = true;
    extraConfigFiles = [templates."synapse/secrets.yaml".path];
    settings = {
      signing_key_path = secrets."synapse/signing_key".path;
      server_name = domain;
      baseurl = "https://${domain}";
      oidc_providers = [];
      settings.listeners = [
        {
          inherit port;
          bind_addresses = ["localhost"];
          type = "http";
          tls = false;
          x_forwarded = true;
          resources = [
            {
              names = ["client" "federation"];
              compress = true;
            }
          ];
        }
      ];
    };
  };

  services.matrix-sliding-sync = {
    enable = true;
    environmentFile = templates."synapse/sliding_sync_env".path;
    settings.SYNCV3_SERVER = "https://${domain}";
  };

  services.nginx.virtualHosts = {
    ${domain} = {
      locations."= /.well-known/matrix/server".extraConfig = mkWellKnown {
        "m.server" = "${fqdn}:443";
      };
      locations."= /.well-known/matrix/client".extraConfig = mkWellKnown {
        "m.homeserver".base_url = "https://${fqdn}";
        "org.matrix.msc3575.proxy"."url" = "https://${fqdn}";
      };
      locations."= /.well-known/matrix/support".extraConfig = mkWellKnown {
        admins = [
          {
            matrix_id = "@tristan:tristans.cloud";
            email_address = "tristan@tristans.cloud";
            role = "admin";
          }
        ];
      };
      locations."/_matrix".proxyPass = "http://localhost:${toString port}";
      locations."/_synapse/client".proxyPass = "http://localhost:${toString port}";
      locations."/_matrix/client/unstable/org.matrix.msc3575/sync".proxyPass = "http://${toString matrix-sliding-sync.settings.SYNCV3_BINDADDR}";
    };
    ${fqdn} = {
      enableACME = true;
      forceSSL = true;
      locations."/_matrix".proxyPass = "http://localhost:${toString port}";
      locations."/_synapse/client".proxyPass = "http://localhost:${toString port}";
      locations."/_matrix/client/unstable/org.matrix.msc3575/sync".proxyPass = "http://${toString matrix-sliding-sync.settings.SYNCV3_BINDADDR}";
    };
  };
}
