{ config, lib, ... }:
let
 cfg = config.syscfg.server;
in {
  config = lib.mkIf (cfg.ipfw.enable) {
    boot.kernel.sysctl = {
      "net.ipv4.ip_forward" = 1;
      "net.ipv6.conf.all.forwarding" = 1;
    };

    networking.nftables.enable = true;
    networking.nftables.ruleset = ''
      table inet nat {
        chain prerouting {
          type nat hook prerouting priority dstnat; policy accept;
          
          ${lib.concatMapStringsSep "\n" (rule:
            let
              srcInt = builtins.elemAt rule 0;
              dstAddr4 = builtins.elemAt rule 1;
              dstAddr6 = builtins.elemAt rule 2;
              srcPort = toString (builtins.elemAt rule 3);
              dstPort = toString (builtins.elemAt rule 4);
            in ''
                iifname "${srcInt}" tcp dport ${srcPort} counter dnat ip to ${dstAddr4}:${dstPort}
                iifname "${srcInt}" udp dport ${srcPort} counter dnat ip to ${dstAddr4}:${dstPort}

                iifname "${srcInt}" tcp dport ${srcPort} counter dnat ip6 to [${dstAddr6}]:${dstPort}
                iifname "${srcInt}" udp dport ${srcPort} counter dnat ip6 to [${dstAddr6}]:${dstPort}
            ''
          ) cfg.ipfw.ports}
        }
        
        chain postrouting {
          type nat hook postrouting priority srcnat; policy accept;
          oifname { ${lib.concatMapStringsSep ", " (iface: ''"${iface}"'') cfg.ipfw.ifs} } masquerade
        }
      }
    '';
  };
}