{ config, lib, ... }:
{
  imports = [ ./nginx ];

  config = lib.mkIf config.services.matrix-synapse.enable {
    services = {
      coturn = {
        enable = true;
        no-cli = true;
        no-tcp-relay = true;
        min-port = 49000;
        max-port = 50000;
        use-auth-secret = true;
        static-auth-secret = config.secrets.coturnSecret;
        realm = "turn.nixfox.ca";
        cert = "/var/lib/acme/${config.services.coturn.realm}/fullchain.pem";
        pkey = "/var/lib/acme/${config.services.coturn.realm}/key.pem";
      };

      # Enable coturn on Synapse
      matrix-synapse.settings = {
        turn_uris = [
          "turn:${config.services.coturn.realm}:3478?transport=udp"
          "turn:${config.services.coturn.realm}:3478?transport=tcp"
        ];
        turn_shared_secret = config.secrets.coturnSecret;
        turn_user_lifetime = "1h";
      };

      cloudflare-dyndns.domains = [ config.services.coturn.realm ];
    };

    networking.firewall = {
      allowedUDPPorts = [
        3478
        5349
      ];
      allowedUDPPortRanges = [{
        from = config.services.coturn.min-port;
        to = config.services.coturn.max-port;
      }];
    };
  };
}
