{ zentralwerk, config, hostRegistry, lib, ... }:

let
  # In theory we could use c3d2.deployment.autoNetSetup, overriding
  # gateway configuration. But it may break silently if anyone would
  # overhaul the networkd configuration file names.
  mac.serv = "02:8b:12:bd:0e:c1";
  mac.pub = "02:8b:12:bd:0e:c2";
in
{
  networking.hostName = "stream";
  c3d2 = {
    deployment = {
      autoNetSetup = false;
      server = "server10";
    };
    hq.statistics.enable = true;
  };

  microvm = {
    mem = 6144;
    interfaces = [ {
      type = "tap";
      id = "serv-stream";
      mac = mac.serv;
    } {
      type = "tap";
      id = "pub-stream";
      mac = mac.pub;
    } ];
  };

  # deployment = {
  #   mem = 6144;
  #   networks = lib.mkForce [ "pub" "serv" ];
  # };

  systemd.network = {
    enable = true;

    # On the serv network I have a static IPv4 and only a route to the
    # rest of the network so that I am reachable by
    # public-access-proxy.

    networks."30-serv" = {
      matchConfig.MACAddress = mac.serv;
      networkConfig.IPv6AcceptRA = false;
      # try harder disabling global ipv6
      networkConfig.LinkLocalAddressing = "no";
      addresses = [{
        addressConfig.Address = "${hostRegistry.stream.ip4}/${toString zentralwerk.lib.config.site.net.serv.subnet4Len}";
      }];
      gateway = lib.mkForce [ ];
      routes = [{
        routeConfig = {
          Destination = "172.20.0.0/14";
          Gateway = hostRegistry.serv-gw.ip4;
        };
      }];
    };

    # On the pub network I am a normal client.
    networks."30-pub" = {
      matchConfig.MACAddress = mac.pub;
      networkConfig.DHCP = "ipv4";
      gateway = lib.mkForce [ ];
      networkConfig.IPv6AcceptRA = true;
    };
  };

  services = {
    jackett.enable = true;

    nginx = {
      # enable = true;
      virtualHosts."stream.hq.c3d2.de" = {
        default = true;
        enableACME = true;
        forceSSL = true;
        locations."/" = {
          proxyPass = "http://127.0.0.1:9000";
          proxyWebsockets = true;
          extraConfig = ''
            auth_basic "Stream";
            auth_basic_user_file ${config.sops.secrets."nginx/httpAuth".path};
          '';
        };
      };
      virtualHosts."torrents.hq.c3d2.de" = {
        enableACME = true;
        forceSSL = true;
        locations."/" = {
          proxyPass = "http://127.0.0.1:9117";
          extraConfig = ''
            auth_basic "Torrents";
            auth_basic_user_file ${config.sops.secrets."nginx/httpAuth".path};
          '';
        };
      };
    };

    peerflix.enable = true;
  };

  systemd.services.peerflix.serviceConfig = {
    Restart = "always";
    RestartSec = 60;
  };

  sops = {
    defaultSopsFile = ./secrets.yaml;
    secrets."nginx/httpAuth".owner = config.systemd.services.nginx.serviceConfig.User;
  };

  system.stateVersion = "22.05";
}
