Syncthing NixOS config

🧩 Syntax:
# To add a machine:
# 1. Generate the certificates with:
# nix-shell -p syncthing --run "syncthing generate"
# 2. Copy the certificates to ${host-secrets}/syncthing-cert.pem and ${host-secrets}/syncthing-cert-key.age:
# cd $NH_FLAKE/nixos-config/hosts/$(cat /etc/hostname)/secrets
# cp ~/.local/state/syncthing/cert.pem $NH_FLAKE/nixos-config/hosts/$(cat /etc/hostname)/secrets/syncthing-cert.pem
# cat ~/.local/state/syncthing/key.pem | agenix -e syncthing-cert-key.age
# 3. Add the device to devices and the relevant folders to folders
{
  config,
  lib,
  host-secrets,
  ...
}:
let
  hostname = config.networking.hostName;

  all-devices = {
    home-server = {
      name = "home-server";
      id = "HZKECY3-AG2MGV6-DCSANPM-CMDJREK-EVVAQLB-NL7EBUX-JOB5KVP-JHT5LQY";
    };
    moonlight = {
      name = "moonlight";
      id = "2QE77OE-6ZX5SVH-FK4K6K6-O2ZQKXD-UYULRNZ-ANV6RIM-4CWMVTW-UJ4HTAH";
    };
  };
  all-folders = {
    "~/Polar" = {
      id = "miniluz-polar";
      devices = [
        "home-server"
        "moonlight"
      ];
      versioning = {
        type = "staggered";
        params = {
          cleanInterval = "3600"; # Clear every hour
          maxAge = "31536000"; # 1 year
        };
      };
    };
  };

  devices = lib.filterAttrs (device: v: device != hostname) all-devices;

  folders-with-hostname = lib.filterAttrs (
    folder-name: folder-config: lib.any (device: device == hostname) folder-config.devices
  ) all-folders;

  folders = lib.mapAttrs (
    folder-name: folder-config:
    lib.mapAttrs (
      config-name: config-value:
      if (config-name == "devices") then
        lib.filter (device: device != hostname) config-value
      else
        config-value
    ) folder-config
  ) folders-with-hostname;

  settings = {
    inherit devices folders;

    options = {
      urAccepted = -1;
    };
  };

  cfg = config.miniluz.selfhosting;
in
{
  options.miniluz.selfhosting.syncthing = lib.mkEnableOption "Syncthing";

  config = lib.mkMerge [
    (lib.mkIf (cfg.enable && cfg.syncthing && cfg.server) {
      age.secrets.syncthing-cert-key.file = "${host-secrets}/syncthing-cert-key.age";

      services.syncthing = {
        enable = true;
        openDefaultPorts = true;

        cert = "${host-secrets}/syncthing-cert.pem";
        key = config.age.secrets.syncthing-cert-key.path;

        inherit settings;
      };
    })
    (lib.mkIf (cfg.enable && cfg.syncthing && !cfg.server) {
      hm = {
        age.secrets.syncthing-cert-key.file = "${host-secrets}/syncthing-cert-key.age";

        services.syncthing = {
          enable = true;

          cert = "${host-secrets}/syncthing-cert.pem";
          key = config.hm.age.secrets.syncthing-cert-key.path;

          inherit settings;
        };
      };
    })
  ];
}