{ pkgs, lib, config, inputs, hostName, ... }:
let
  inherit (config.users) users;
  pumpkin2off2 = conf: lib.mapAttrs (_n: v: lib.recursiveUpdate v conf) {
    "pumpkin/root" = let targetHost = "aubergine.local"; in {
      target = "backup@${targetHost}:off2/julm/backup/pumpkin";
      sendOptions = "raw";
      recursive = true;
      extraArgs = [
        "--create-bookmark" "--no-sync-snap" "--no-privilege-elevation"
        "--preserve-properties" "--preserve-recordsize"
        "--recursive" "--sendoptions=w" "--recvoptions=u"
        "--exclude" "pumpkin/root/nix"
        "--exclude" "pumpkin/root/var/cache"
        "--exclude" "pumpkin/root/var/log"
        "--exclude" "pumpkin/root/home/julm/.cache"
        "--sshconfig" "${pkgs.writeText "ssh-config" ''
            Host *
              Ciphers aes128-gcm@openssh.com
              Compression no
              StrictHostKeyChecking yes
              UserKnownHostsFile ${pkgs.writeText "known_hosts" ''
                ${targetHost} ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIN/cT/L3dF7uoR3s7NB59NiKjuk35I6x+7MK5zhwOy6k
              ''}
        ''}"
      ];
    };
  };
in
{
  networking.nftables.ruleset = lib.mkAfter ''
    table inet filter {
      chain output-net {
        skuid @nixos_syncoid_uids \
          meta l4proto tcp \
          counter accept \
          comment "syncoid: SSH"
      }
    }
  '';
  systemd.tmpfiles.rules = [
    "z /dev/zfs 0660 - ${config.users.groups."disk".name}  -"
  ];
  # ExplanationNote: give access to /var/run/avahi-daemon/socket
  # Using /var/run is not working due to RootDirectoryStartOnly=true
  systemd.services.syncoid-pumpkin-root.serviceConfig.BindReadOnlyPaths = [ "/var/run" ];
  systemd.services.syncoid-pumpkin-root.serviceConfig.RootDirectoryStartOnly = lib.mkForce false;
  systemd.services.syncoid-pumpkin-root.serviceConfig.ExecStartPost = pkgs.writeShellScript "zfs-fix-bookmarks" ''
      set -ux
      for s in $(zfs list -Hrpt snapshot -o name pumpkin); do
        zfs bookmark "$s" "''${s//@/#}" || true
      done
  '';
  services.syncoid = {
    enable = true;
    interval = "*-*-* *:05:00";
    #interval = "*:0/1";
    sshKey = "ssh.key:${syncoid/ssh.key.cred}";
    commonArgs = [
      #"--debug"
      "--no-sync-snap"
      "--create-bookmark"
      #"--no-privilege-elevation"
      #"--no-stream"
      #"--preserve-recordsize"
      #"--preserve-properties"
    ];
    service = {
      serviceConfig.Group = config.users.groups."disk".name;
    };
    commands = { }
    // pumpkin2off2 { }
    ;
  };
}