# Sources for this configuration:
# - https://github.com/qbittorrent/qBittorrent/wiki/NGINX-Reverse-Proxy-for-Web-UI
# - https://github.com/qbittorrent/qBittorrent/wiki/Linux-WebUI-HTTPS-with-Let's-Encrypt-certificates-and-NGINX-SSL-reverse-proxy

{ ... }:
{
  services.nginx = {
    enable = true;

    virtualHosts."torrent.grzb.de" = {
      forceSSL = true;
      enableACME = true;

      listen = [
        {
          addr = "0.0.0.0";
          port = 80;
        }
        {
          addr = "0.0.0.0";
          port = 443;
          ssl = true;
        }
      ];

      locations."/" = {
        proxyPass = "http://127.0.0.1:8080";
        extraConfig = ''
          proxy_http_version 1.1;

          client_max_body_size 100M;

          # From:
          # https://github.com/qbittorrent/qBittorrent/wiki/NGINX-Reverse-Proxy-for-Web-UI
          #
          # Since v4.2.2, is possible to configure qBittorrent
          # to set the "Secure" flag for the session cookie automatically.
          # However, that option does nothing unless using qBittorrent's built-in HTTPS functionality.
          # For this use case, where qBittorrent itself is using plain HTTP
          # (and regardless of whether or not the external website uses HTTPS),
          # the flag must be set here, in the proxy configuration itself.
          # Note: If this flag is set while the external website uses only HTTP, this will cause
          # the login mechanism to not work without any apparent errors in console/network resulting in "auth loops".
          proxy_cookie_path  /                  "/; Secure";
        '';
      };
    };
  };

  networking.firewall.allowedTCPPorts = [ 80 443 ];
}