{ config, pkgs, ... }: { sops.secrets.wireguard_home = { sopsFile = ../secrets/wireguard.yaml; key = "wireguard_home_conf"; path = "/run/secrets/Home.conf"; restartUnits = [ "wireguard-home.service" ]; }; systemd.services.wireguard-home = { description = "Import Home WireGuard connection into NetworkManager"; wantedBy = [ "multi-user.target" ]; after = [ "NetworkManager.service" "sops-nix.service" ]; wants = [ "NetworkManager.service" "sops-nix.service" ]; serviceConfig = { Type = "oneshot"; RemainAfterExit = true; }; script = '' set -euo pipefail new_hash=$( ${pkgs.coreutils}/bin/sha256sum /run/secrets/Home.conf | ${pkgs.coreutils}/bin/cut -d' ' -f1 ) old_hash=$( ${pkgs.coreutils}/bin/cat /var/lib/wireguard-home/hash 2>/dev/null || true ) if [ "$new_hash" = "$old_hash" ]; then echo "Home WireGuard configuration unchanged." exit 0 fi echo "Home WireGuard configuration changed; updating NetworkManager..." # Remember whether Home was active before replacing it. if ${pkgs.networkmanager}/bin/nmcli -t -f NAME,ACTIVE connection show \ | ${pkgs.gnugrep}/bin/grep -q '^Home:yes$'; then home_was_active=true else home_was_active=false fi ${pkgs.networkmanager}/bin/nmcli connection delete Home || true ${pkgs.networkmanager}/bin/nmcli connection import \ type wireguard \ file /run/secrets/Home.conf # Make it not autoconnect on reboot ${pkgs.networkmanager}/bin/nmcli connection modify Home connection.autoconnect no # Only re-enable it if it was active before the update. if [ "$home_was_active" = true ]; then ${pkgs.networkmanager}/bin/nmcli connection up Home else ${pkgs.networkmanager}/bin/nmcli connection down Home echo "Home was not active; disabling just to be sure." fi ${pkgs.coreutils}/bin/mkdir -p /var/lib/wireguard-home echo "$new_hash" > /var/lib/wireguard-home/hash ''; }; systemd.tmpfiles.rules = [ "d /var/lib/wireguard-home 0755 root root -" ]; }