{ config, pkgs, ... }:
let
  webUIport = 55555;
  forwardPort = 8888;
  torrentPort = 49114;
  namespace = "wg-mullvad-namespace";
  interface = "wg-mullvad";
in
{
  users.users.qbittorrent.extraGroups = [ "media" ];
  services.qbittorrent = {
    enable = true;
    webuiPort = webUIport;
    serverConfig = {
      LegalNotice.Accepted = true;
      Preferences = {
        WebUI = {
	  StatusbarExternalIPDisplayed = true;
	  HostHeaderValidation = false;
          Username = "admin";
          Password_PBKDF2 = "@ByteArray(WHjV8k2o78gWuL4xAUu0Ww==:eSOIQzJvNmW2JNbvC5DsS3h4JxAvkqJ0g0o1STTLplWLq9cDPjBME3/+dJ/c+p2crLIP2JEoO7KzD0JvLlU9TA==)";
        };
        General.Locale = "en";
      };
      BitTorrent = {
        Session = {
	  Port = torrentPort;
	  GlobalMaxRatio = 5;
	  ShareLimitAction = "RemoveWithContent";
	  QueueingSystemEnabled = false;
	  DefaultSavePath = "/var/lib/torrents";
	  Interface = interface;
	  InterfaceName = interface;
	  MaxConnections = -1;
          MaxConnectionsPerTorrent = -1;
          MaxUploads = -1;
          MaxUploadsPerTorrent = -1;
	};
      };
    };
  };

  systemd.services.qbittorrent.serviceConfig = {
    NetworkNamespacePath = "/var/run/netns/${namespace}";
    BindReadOnlyPaths = [
      "/etc/netns/${namespace}/resolv.conf:/etc/resolv.conf"
    ];
  };
  systemd.services.qbittorrent.after = [ "wireguard-${interface}.target" ];

  systemd.services.forward-namespace = {
    description = "Proxy LAN to VPN namespace";
    after = [ "network.target" ];
    wantedBy = [ "multi-user.target" ];
    script = "${pkgs.socat}/bin/socat TCP-LISTEN:${toString forwardPort},fork,reuseaddr TCP:10.200.200.2:${toString webUIport}";
  };

  systemd.tmpfiles.rules = [
    "d /var/lib/torrents 0750 qbittorent qbittorrent -"
  ];
}
