{
  config,
  flake,
  pkgs,
  ...
}:
let
  inherit (flake.config.people) user0;
  inherit (flake.config.services) instances;
  serviceCfg = instances.torrent;
  host = instances.torrent.domains.url0;
  dns0 = instances.web.dns.provider0;
  dns0Path = "dns/${dns0}";
  torrentPort = 2049;
in
{
  microvm.vms.${serviceCfg.name} = {
    autostart = true;
    config = {
      system.stateVersion = "25.05";

      networking = {
        wg-quick.interfaces = {
          wg0 = {
            address = [
              "172.22.116.126/32"
              "fd00:4956:504e:ffff::ac16:747e/128"
            ];
            dns = [ "172.16.0.1" ];
            privateKeyFile = "/run/secrets/wireguard-pass";
            peers = [
              {
                publicKey = "hku9gjamhoii8OvxZgx+TdUDIkOAQYFu39qbav2AyUQ=";
                endpoint = "89.187.181.116:${builtins.toString torrentPort}";
                allowedIPs = [
                  "0.0.0.0/0"
                  "::/0"
                ];
                persistentKeepalive = 25;
              }
            ];
          };
        };
        firewall = {
          enable = true;
          allowedTCPPorts = [
            22
            torrentPort
            serviceCfg.ports.port0
          ];
          allowedUDPPorts = [
            torrentPort
          ];
        };
        dhcpcd.enable = false;
        useNetworkd = true;
      };

      # imports = [
      #   ./rqbit.nix
      # ];

      services = {
        qbittorrent = {
          enable = true;
          webuiPort = serviceCfg.ports.port0;
          torrentingPort = torrentPort;
          openFirewall = true;
          serverConfig = {
            LegalNotice.Accepted = true;

            BitTorrent = {
              Session = {
                Interface = "wg0";
                InterfaceName = "wg0";
                MaxConnections = -1;
                Port = torrentPort;
                MaxConnectionsPerTorrent = -1;
                MaxUploads = -1;
                MaxUploadsPerTorrent = -1;
              };
            };

            Preferences = {
              WebUI = {
                Username = "user";
                # generate new passwords with this:
                # https://codeberg.org/feathecutie/qbittorrent_password
                Password_PBKDF2 = "@ByteArray(1bJKXLVSLU6kgCHbCS2lDg==:BmyrMaod6dbJqEe7Ud/JgKAxRMqzsAuEjHcTvLzIBgc5rc5Z7J2X9mbH0cDEAhXqc+O3gQxrckt8S2Gf+zlO9w==)";
              };

              General = {
                Locale = "en";
              };
              Downloads = {
                SavePath = "${serviceCfg.varPaths.path0}/downloads";
                TempPathEnabled = false;
                PreAllocation = false;
              };
            };
          };
        };

        openssh = {
          enable = true;
          settings.PasswordAuthentication = false;
        };
      };

      users.users.root.openssh.authorizedKeys.keys = flake.config.people.users.${user0}.sshKeys;

      systemd = {
        network = {
          enable = true;
          networks."10-enp" = {
            matchConfig.Name = "enp0s5";
            addresses = [ { Address = "${serviceCfg.interface.ip}/24"; } ];
            gateway = [ serviceCfg.interface.gate ];
          };
        };

        tmpfiles.rules = [
          "d ${serviceCfg.varPaths.path0} 755 ${serviceCfg.name} ${serviceCfg.name} -"
          "d ${serviceCfg.varPaths.path0}/downloads 755 ${serviceCfg.name} ${serviceCfg.name} -"
        ];

        services.qbittorrent = {
          after = [ "wg-quick-wg0.service" ];
          requires = [ "wg-quick-wg0.service" ];
        };
      };

      microvm = {
        vcpu = 1;
        mem = 1024 * 1;
        hypervisor = "qemu";

        interfaces = [
          {
            type = "tap";
            id = serviceCfg.interface.id;
            mac = serviceCfg.interface.mac;
          }
          {
            type = "user";
            id = serviceCfg.interface.idUser;
            mac = serviceCfg.interface.macUser;
          }
        ];

        forwardPorts = [
          {
            from = "host";
            host.port = serviceCfg.interface.ssh;
            guest.port = 22;
          }
        ];

        shares = [
          {
            source = "/nix/store";
            mountPoint = "/nix/.ro-store";
            tag = "ro-store";
            proto = "virtiofs";
          }
          {
            mountPoint = serviceCfg.varPaths.path0;
            proto = "virtiofs";
            source = serviceCfg.mntPaths.path0;
            tag = "${serviceCfg.name}_data";
          }
          {
            mountPoint = "/run/secrets";
            proto = "virtiofs";
            source = "/run/secrets/proton";
            tag = "host_secrets";
          }
        ];
      };

      environment.systemPackages = with pkgs; [
        wireguard-tools
        speedtest-go
      ];
    };
  };

  services = {
    caddy = {
      virtualHosts = {
        "${host}" = {
          extraConfig = ''
            basic_auth {
              {$CADDY_AUTH_USER} {$CADDY_AUTH_PASSWORD_HASH}
            }
            reverse_proxy ${serviceCfg.interface.ip}:${toString serviceCfg.ports.port0}

            tls ${serviceCfg.ssl.cert} ${serviceCfg.ssl.key}

            encode zstd gzip
          '';
        };
      };
    };
  };

  sops.secrets = {
    "caddy/share-auth" = {
      owner = "caddy";
      group = "caddy";
      mode = "0400";
    };
    "proton/wireguard-pass" = {
      owner = "root";
      mode = "0400";
    };
  };

  security.acme.certs."${host}" = {
    dnsProvider = dns0;
    environmentFile = config.sops.secrets.${dns0Path}.path;
    group = "caddy";
  };

  users.users.caddy.extraGroups = [ "acme" ];

  systemd = {
    services.caddy = {
      serviceConfig = {
        EnvironmentFile = config.sops.secrets."caddy/share-auth".path;
      };
    };
    tmpfiles.rules = [
      "d ${serviceCfg.mntPaths.path0} 0755 microvm wheel - -"
      "d ${serviceCfg.secretPaths.path0}/caddy 755 caddy caddy -"
      "d /var/log/caddy 755 caddy caddy -"
    ];
  };
}
