{ inputs, pkgs, lib, hosts, config, ... }: let inherit (config.networking) hostName; inherit (inputs.self.packages.${pkgs.system}) hyprspace; hyprspaceCapableNodes = lib.filterAttrs (_: host: host ? hypr) hosts; peersFormatted = builtins.mapAttrs (_: x: { "${x.hypr.addr}".id = x.hypr.id; }) hyprspaceCapableNodes; peersFiltered = lib.filterAttrs (name: _: name != hostName) peersFormatted; buildHyprspacePeerList = peers: pkgs.writeText "hyprspace-peers.yml" (builtins.toJSON peers); peers = lib.foldAttrs (n: _: n) null (builtins.attrValues peersFiltered); peerList = buildHyprspacePeerList peers; myNode = hosts.${hostName}; listenPort = myNode.hypr.listenPort or 8001; precedingConfig = pkgs.writeText "hyprspace-interface.yml" '' interface: name: hyprspace listen_port: ${builtins.toString listenPort} id: ${myNode.hypr.id} address: ${myNode.hypr.addr}/24 private_key: !!binary | ''; privateKeyFile = config.age.secrets.hyprspace-key.path; runConfig = "/run/hyprspace.yml"; in { networking.hosts = lib.mapAttrs' (k: v: lib.nameValuePair (v.hypr.addr) ([k "${k}.hypr"])) hyprspaceCapableNodes; age.secrets.hyprspace-key = { file = ../../secrets/hyprspace-key- + "${hostName}.age"; mode = "0400"; }; age.secrets.ipfs-swarm-key = { file = ../../secrets/ipfs-swarm-key.age; mode = "0400"; }; systemd.services.hyprspace = { enable = true; wantedBy = [ "multi-user.target" ]; wants = [ "network-online.target" ]; after = [ "network-online.target" ]; preStart = '' test -e ${runConfig} && rm ${runConfig} touch ${runConfig} chmod 0600 ${runConfig} cat ${precedingConfig} >> ${runConfig} sed 's/^/ /g' ${privateKeyFile} >> ${runConfig} echo -n 'peers: ' >> ${runConfig} cat ${peerList} >> ${runConfig} chmod 0400 ${runConfig} ''; environment.HYPRSPACE_SWARM_KEY = config.age.secrets.ipfs-swarm-key.path; serviceConfig = { ExecStart = "${hyprspace}/bin/hyprspace up hyprspace -f -c ${runConfig}"; ExecStop = "${hyprspace}/bin/hyprspace down hyprspace"; }; }; networking.firewall = { allowedTCPPorts = [ listenPort ]; allowedUDPPorts = [ listenPort ]; trustedInterfaces = [ "hyprspace" ]; }; networking.networkmanager.dispatcherScripts = [{ source = pkgs.writeShellScript "hyprspace-reconnect.sh" '' [[ "$2" != "up" ]] && exit 0 PATH=${pkgs.systemd}/bin:$PATH case $1 in wl*|en*) if systemctl is-active hyprspace.service; then ${builtins.concatStringsSep "\n" (map (peer: "/run/wrappers/bin/ping -qnA -c3 -W1 ${peer} && exit") (builtins.attrNames peers))} fi systemctl restart --no-block hyprspace.service;; esac exit 0 ''; type = "basic"; }]; }