{config, pkgs, ...}:

{
  systemd.targets.machines.enable = true;
  systemd.services."pterodactyl-container" = {
    enable = true;
    wantedBy = ["machines.target"];
    environment = {
      # SYSTEMD_NSPAWN_USE_CGNS = "0";
    };
    script = ''
      exec ${config.systemd.package}/bin/systemd-nspawn --hostname pterodactyl \
        --resolv-conf=off --system-call-filter="add_key keyctl bpf" --bind /dev/fuse \
        -nbD /var/lib/machines/pterodactyl --machine pterodactyl
    '';
    postStart = ''
      ${pkgs.iproute2}/bin/ip link set ve-pterodactyl up || true
      ${pkgs.iproute2}/bin/ip addr add 10.1.0.0 dev ve-pterodactyl || true
      ${pkgs.iproute2}/bin/ip route add 10.1.0.1 dev ve-pterodactyl || true
    '';
    serviceConfig = {
      Type = "notify";
      Slice = "machine.slice";
      Delegate = true;
      DeviceAllow = "/dev/fuse rwm";
    };
  };
  networking.nat = {
    enable = true;
    # Check for hostBridge use vb instead of ve
    internalInterfaces = ["ve-pterodactyl"];
    externalInterface = "enp0s25";
    enableIPv6 = true;
    forwardPorts = [
     { sourcePort = "25565:26000";
       destination = "10.1.0.1:25565-25600";
       proto = "tcp";
     }
     { sourcePort = "25565:26000";
       destination = "10.1.0.1:25565-25600";
       proto = "udp";
     }
     { sourcePort = 2022;
       destination = "10.1.0.1:2022";
       proto = "tcp";
     }
     { sourcePort = 2022;
       destination = "10.1.0.1:2022";
       proto = "udp";
     }
    ];
  };
  services.caddy.virtualHosts = {
    "games.syzygial.cc:443" = {
      serverAliases = [
        "games.crompton.cc:443"
      ];
      extraConfig = ''
        reverse_proxy 10.1.0.1:80
      '';
    };
    "games.syzygial.cc:9000" = {
      serverAliases = [
        "games.crompton.cc:9000"
      ];
      extraConfig = ''
        reverse_proxy 10.1.0.1:9000
      '';
    };
    "pnode.syzygial.cc:443" = {
      extraConfig = ''
        reverse_proxy 10.1.0.1:9000
      '';
    };
    "pnode.syzygial.cc:9000" = {
      extraConfig = ''
        reverse_proxy 10.1.0.1:9000
      '';
    };
  };
}
