{ pkgs, lib, config, inputs, hostName, ... }:
let
  inherit (config.boot) initrd;
  wgIface = "wg-intra";
  peers = import (inputs.julm-nix + "/nixos/profiles/wireguard/${wgIface}/peers.nix");
in
{
  # Open a wireguard tunnel to a relay
  # in case the host is hosted behind a NAT and has no SSH port forwarding.
  # This enables to send the disk password to the initrd, like that:
  # ssh -J mermet.sp root@losurdo.sp -p 2222
  # TODO: use a dedicated interface wg-initrd
  security.initrd.secrets."${hostName}/wireguard/${wgIface}/privateKey" =
    "hosts/${hostName}/wireguard/${wgIface}/privateKey.gpg";
  boot.initrd.kernelModules = [ "wireguard" ];
  boot.initrd.network.flushBeforeStage2 = true;
  boot.initrd.systemd = {
    initrdBin = [
      pkgs.iproute2
      pkgs.iputils
      pkgs.wireguard-tools
    ];
    services.systemd-networkd = {
      serviceConfig.LoadCredential = [ "${wgIface}.key:${config.security.initrd.stage1Dir}/${hostName}/wireguard/${wgIface}/privateKey" ];
    };
    network = {
      netdevs = {
        "50-${wgIface}" = {
          netdevConfig = {
            Kind = "wireguard";
            Name = wgIface;
            MTUBytes = "1280";
          };
          wireguardConfig = {
            PrivateKeyFile = "/run/credentials/systemd-networkd.service/${wgIface}.key";
            ListenPort = peers.${hostName}.listenPort;
          };
          wireguardPeers = [
            {
              wireguardPeerConfig = with peers.mermet.peer; {
                AllowedIPs = allowedIPs;
                Endpoint = endpoint;
                PersistentKeepalive = peers.${hostName}.persistentKeepalive;
                PublicKey = publicKey;
              };
            }
            {
              wireguardPeerConfig = with peers.oignon.peer; {
                AllowedIPs = allowedIPs;
                PersistentKeepalive = peers.${hostName}.persistentKeepalive;
                PublicKey = publicKey;
              };
            }
          ];
        };
      };
      networks.${wgIface} = {
        name = wgIface;
        address = peers.${hostName}.ips;
        /*
        networkConfig = {
          IPMasquerade = "ipv4";
          IPForward = true;
        };
        */
      };
    };
  };
}