{ config, ... }:

{
  services.nginx = {
    enable = true;

    virtualHosts."acme-matrix.hamburg.ccc.de" = {
      default = true;
      enableACME = true;
      serverName = "matrix.hamburg.ccc.de";

      listen = [
        {
          addr = "0.0.0.0";
          port = 31820;
        }
      ];
    };

    virtualHosts."matrix.hamburg.ccc.de" = {
      default = true;
      forceSSL = true;
      useACMEHost = "matrix.hamburg.ccc.de";

      listen = [
        {
          addr = "0.0.0.0";
          port = 8443;
          ssl = true;
          proxyProtocol = true;
        }
        {
          addr = "0.0.0.0";
          port = 8448;
          ssl = true;
          proxyProtocol = true;
        }
      ];

      locations."~ ^(/_matrix|/_synapse/client)" = {
        # Only proxy to the local host on IPv4, because localhost doesn't seem to work
        # even if matrix-synapse is listening on ::1 as well.
        proxyPass = "http://127.0.0.1:8008";
        extraConfig = ''
          # Nginx by default only allows file uploads up to 1M in size
          # Increase client_max_body_size to match max_upload_size defined in homeserver.yaml
          client_max_body_size ${config.services.matrix-synapse.settings.max_upload_size};
        '';
      };

      extraConfig = ''
        # Make use of the ngx_http_realip_module to set the $remote_addr and
        # $remote_port to the client address and client port, when using proxy
        # protocol.
        # First set our proxy protocol proxy as trusted.
        set_real_ip_from 172.31.17.140;
        # Then tell the realip_module to get the addreses from the proxy protocol
        # header.
        real_ip_header proxy_protocol;
      '';
    };
  };

  networking.firewall.allowedTCPPorts = [ 8443 8448 31820 ];
}