{ config, lib, pkgs, ... }: let

  isValidPeer = p: 
    (p ? syscfg.net.wg.enable) && 
    (p.syscfg.net.wg.enable == true) && 
    (p.syscfg.net.wg.pubkey != config.syscfg.net.wg.pubkey);
  activePeers = builtins.filter isValidPeer config.syscfg.peers;
in
{
  config = lib.mkIf (config.syscfg.net.wg.enable) {
    networking.wireguard = {
      enable = true;
      interfaces = {
        wg0 = {
          ips = [ config.syscfg.net.wg.ip4 config.syscfg.net.wg.ip6 ];
          privateKeyFile =
            config.sops.secrets."${config.syscfg.hostname}_wg_priv".path;
          listenPort = 1515;
          mtu = 1340;
          peers = 
            if (config.syscfg.server ? wireguard && config.syscfg.server.wireguard) then
              map (p: {
                name = p.syscfg.hostname;
                publicKey = p.syscfg.net.wg.pubkey;
                allowedIPs = [ p.syscfg.net.wg.ip4 p.syscfg.net.wg.ip6 ];
              }) activePeers
            else
              [{
                allowedIPs = [ "10.10.1.0/24" "fd10:10:10::0/64" ];
                name = "vpn-helcel";
                endpoint = "vpn.helcel.net:1515";
                publicKey = "NFBJvYXZC+bd62jhrKnM7/pugidWhgR6+C5qIiUiq3Q=";
                persistentKeepalive = 30;
              }];
        };
      };
    };

    systemd.services."wireguard-wg0-peer-vpn-helcel" = {
      after = [ "network-online.target" "nss-lookup.target" ];
      bindsTo = [ "network-online.target" ];
      wantedBy = lib.mkForce [ "network-online.target" ];
      before =  lib.mkForce [ ];
      serviceConfig = {
        Restart = "on-failure";
        RestartSec = "10s";          # Wait 2 seconds before retrying the domain query
      };
      startLimitIntervalSec = 0;  
    };
  };
}
