{ pkgs, config, ... }:
let
  kopiaPkg = pkgs.unstable.kopia;
  kopia = "${kopiaPkg}/bin/kopia";
  btrfsPkg = pkgs.btrfs-progs;
  btrfs = "${btrfsPkg}/bin/btrfs";
  snapshotBackup = pkgs.writeScript "kopia-snapshot-backup" (builtins.readFile ./kopia-snapshot-backup.sh);
  backupScript = pkgs.writeShellScript "backup-persist" ''
      target_path="${config.custom.impermanence.persistPath}"
      KOPIA_CHECK_FOR_UPDATES=false

      ${kopia} repository connect server \
        --url https://fractal:51515/ \
        --server-cert-fingerprint=a79fce88b1d53ab9e58b8aab20fd8c82332492d501f3ce3efc5e2bb416140be5 \
        -p "$(cat ${config.sops.secrets.kopia.path})" \
      || exit 1

      # Check if target_path is on btrfs filesystem
      fs_type=$(stat -f -c %T "$target_path")

      if [ "$fs_type" = "btrfs" ]; then
        # On btrfs: use snapshot for consistency
        snapshot_path="$target_path/kopia-backup-snapshot"
        [ -e "$snapshot_path" ] && ${btrfs} subvolume delete "$snapshot_path"
        ${btrfs} subvolume snapshot -r "$target_path" "$snapshot_path"

        # --no-send-snapshot-path due to https://github.com/kopia/kopia/issues/4402
        # Exclude btrfs replication snapshots (they appear as empty dirs in the snapshot anyway)
        ${kopia} snapshot create --no-send-snapshot-report --override-source "$target_path" \
          --ignore "services@*" \
          --ignore "services-standby/services@*" \
          -- "$snapshot_path"

        ${btrfs} subvolume delete "$snapshot_path"
      else
        # On non-btrfs (e.g., ext4): backup directly without snapshot
        ${kopia} snapshot create --no-send-snapshot-report --override-source "$target_path" \
          -- "$target_path"
      fi

      ${kopia} repository disconnect
  '';
in
{
  environment.systemPackages = [ 
    btrfsPkg
    kopiaPkg
  ];

  systemd = {
    services."backup-persist" = {
      description = "Backup persistent data with Kopia";
      serviceConfig = {
        Type = "oneshot";
        User = "root";
        ExecStart = "${backupScript}";
      };
    };

    timers."backup-persist" = {
      description = "Timer for Kopia persistent data backup";
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnCalendar = "hourly";
        RandomizedDelaySec = 300;
      };
    };
  };
}
