{ lib, mediaStackPaths, ... }:
let
  webPort = 8081;
  btPort = 51413;
  inherit (mediaStackPaths) downloadsDir downloadsIncompleteDir qbittorrentDataDir;
in
{
  services.qbittorrent = {
    enable = true;
    openFirewall = true;
    webuiPort = webPort;
    torrentingPort = btPort;
  };

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

  fileSystems."/var/lib/qbittorrent" = {
    device = qbittorrentDataDir;
    fsType = "none";
    neededForBoot = false;
    options = [
      "bind"
      "nofail"
      "x-systemd.after=mnt-media\\x2dmedia\\x2dstack.mount"
    ];
  };

  networking.firewall.allowedTCPPorts = [ webPort btPort ];
  networking.firewall.allowedUDPPorts = [ btPort ];

  # Default save path for new torrents (existing qBittorrent.conf may override after migration).
  systemd.services.qbittorrent.preStart = lib.mkAfter ''
    mkdir -p ${downloadsDir} ${downloadsIncompleteDir}
    chmod 2775 ${downloadsDir} ${downloadsIncompleteDir}
    chgrp media ${downloadsDir} ${downloadsIncompleteDir}
  '';
}
