{ config, lib, ... }:
let
  webPort = 8081;
  btPort = 51413;
  downloadsDir = "/var/lib/downloads";
in
{
  # qBittorrent (headless). Web UI: http://<host>:8081
  services.qbittorrent = {
    enable = true;
    openFirewall = true;
    webuiPort = webPort;
    # Prefer a stable port for NAT/firewall and for easier debugging.
    torrentingPort = btPort;
  };

  users.groups.qbittorrent = { };
  users.users.qbittorrent = {
    isSystemUser = true;
    group = "qbittorrent";
    extraGroups = [ "media" ];
  };

  systemd.tmpfiles.settings."nix-server-downloads-dir" = {
    "${downloadsDir}"."d" = {
      mode = "2775";
      user = "root";
      group = "media";
    };
  };

  # Some NixOS versions don't open UDP for torrenting even when openFirewall=true.
  networking.firewall.allowedTCPPorts = [ webPort btPort ];
  networking.firewall.allowedUDPPorts = [ btPort ];
}

