#!/usr/bin/env bash
# backup-maint/apply — prune or test-restore, run ON THE STORAGE NODE against the local repo
# directory (only root there can prune: the rest-server itself is append-only).
#
# params: {"repoDir":"/srv/backups/<user>","repoPassword":"…","planId":"…","action":"prune|test-restore",
#          "keepDaily":7,"keepWeekly":4,"keepMonthly":6}
# prune outputs:        remaining, snapshotIds[], checkOk
# test-restore outputs: snapshotId, filesExpected, filesRestored, verified
set -euo pipefail
. "$(dirname "$0")/../lib/backup-common.sh"
P=$(cat)
backup_init "$P"
PLAN="$BACKUP_PLAN"; [ -n "$PLAN" ] || die "planId is required"
ACTION=$(jq -r '.action // empty' <<<"$P")
W=$(mktemp -d)
SCRATCH="$BACKUP_STATE_DIR/scratch/$PLAN"
BACKUP_ON_EXIT='rm -rf "$W" "$SCRATCH"'

run_restic() { # label args... ; capture stderr, report its last line on failure
  local label="$1" rc=0; shift
  restic "$@" > "$W/out" 2> "$W/err" || rc=$?
  if [ "$rc" -ne 0 ]; then echo "restic $label failed (exit $rc): $(backup_last_line "$W/err")" >&2; exit "$rc"; fi
}
int() { [[ "${2:-}" =~ ^[0-9]{1,4}$ ]] || die "$1 must be a number"; echo "$2"; }

case "$ACTION" in
  prune)
    kd=$(int keepDaily "$(jq -r '.keepDaily // 7' <<<"$P")")
    kw=$(int keepWeekly "$(jq -r '.keepWeekly // 4' <<<"$P")")
    km=$(int keepMonthly "$(jq -r '.keepMonthly // 6' <<<"$P")")
    run_restic forget forget --prune --keep-daily "$kd" --keep-weekly "$kw" --keep-monthly "$km" --tag "plan:$PLAN"
    run_restic check check
    run_restic snapshots snapshots --json --tag "plan:$PLAN"
    jq -c '{remaining:length, snapshotIds:[.[].id], checkOk:true}' "$W/out" > "$SSR_OUTPUTS"
    ;;
  test-restore)
    rm -rf "$SCRATCH"; mkdir -p "$SCRATCH"; chmod 0700 "$SCRATCH"
    run_restic snapshots snapshots --json --tag "plan:$PLAN"
    SNAP=$(jq -r 'if length==0 then empty else max_by(.time).id end' "$W/out")
    [ -n "$SNAP" ] || die "no snapshots for plan $PLAN"
    run_restic restore restore "$SNAP" --target "$SCRATCH" --verify
    run_restic ls ls --json "$SNAP"
    expected=$(jq -s 'map(select(.type=="file"))|length' "$W/out")
    restored=$(find "$SCRATCH" -type f | wc -l | tr -d ' ')
    if [ "$restored" -ne "$expected" ]; then
      echo "test-restore: restored $restored of $expected files" >&2; exit 2
    fi
    jq -n --arg s "$SNAP" --argjson e "$expected" --argjson r "$restored" \
      '{snapshotId:$s,filesExpected:$e,filesRestored:$r,verified:true}' > "$SSR_OUTPUTS"
    ;;
  *) die "action must be prune or test-restore";;
esac
