#!/usr/bin/env bash
# backup-restore/apply — restore from a restic snapshot: files to a safe path, files in place (guarded),
# or a postgres dump into a running container.
#
# params (common): {"repo":"rest:http://10.13.13.2:8000/<user>/","user":"…","password":"…","repoPassword":"…",
#                   "planId":"…","snapshotId":"<hex>","mode":"files-to-path|files-in-place|postgres-container"}
#   (top-level user/password are the rest-server credentials; the database user is "dbUser")
#   files-to-path:      "paths":["/abs"…], "targetDir":"/srv/restore/<id>"  (must be absent or empty)
#   files-in-place:     "paths":["/abs"…], "overwrite":true     (refused for system roots)
#   postgres-container: "name":"sdp-db", "container":"…", "database":"…", "dbUser":"…"
# outputs: snapshotId, mode, filesExpected, filesRestored, bytesRestored, verified (+ restoredRoots | database, publicTables)
# exit 2 = restored files do not match the snapshot's (count, size, or a requested path is absent).
set -euo pipefail
. "$(dirname "$0")/../lib/backup-common.sh"
P=$(cat)
backup_init "$P"
PLAN="$BACKUP_PLAN"; [ -n "$PLAN" ] || die "planId is required"
W=$(mktemp -d)
SCRATCH="$BACKUP_STATE_DIR/restore/$PLAN"
# the exit trap removes ONLY the work dir and the postgres scratch dir, never a targetDir
BACKUP_ON_EXIT='rm -rf "$W" "$SCRATCH"'
RROOT="${SSR_RESTORE_ROOT:-/}"            # in-place target; overridable for tests only
TBASE="${SSR_RESTORE_BASE:-/srv/restore}"  # files-to-path confinement; overridable for tests only

NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$'
PATH_RE='^/[A-Za-z0-9._/@+-]*$'
SNAP=$(jq -r '.snapshotId // empty' <<<"$P")
[[ "$SNAP" =~ ^[0-9a-f]{8,64}$ ]] || die "invalid snapshotId"
MODE=$(jq -r '.mode // empty' <<<"$P")

norm() { # collapse // and trailing /
  local x; x=$(sed -E 's#/+#/#g' <<<"$1"); [ "$x" = / ] || x="${x%/}"; printf '%s' "$x"
}
valid_path() { [[ "$1" =~ $PATH_RE ]] && [[ "$1" != *"/../"* && "$1" != */.. && "$1" != *"/./"* && "$1" != */. ]]; }
PROTECTED=(/etc /usr /boot /bin /sbin /lib /lib64 /lib32 /libx32 /run /proc /sys /dev /var/lib/docker /root)
ALLOW_RE='^/root/\.gnupg(/|$)|^/root/\.aptly\.conf$'
is_protected() { # normalized path; equal to or under a protected root. $2=allow: apply the /root allow-list (in-place only)
  local p="$1" r
  [ "$p" = / ] && return 0
  if [ "${2:-}" = allow ] && [[ "$p" =~ $ALLOW_RE ]]; then return 1; fi
  if [[ "$p" =~ ^/[^/]+$ ]]; then return 0; fi      # directly under /
  for r in "${PROTECTED[@]}"; do
    if [ "$p" = "$r" ] || [[ "$p" == "$r"/* ]]; then return 0; fi
  done
  return 1
}
# protected either literally or after resolving symlinks
is_protected_any() { # path [allow]
  local res; res=$(realpath -m -- "$1")
  is_protected "$1" "${2:-}" || is_protected "$res" "${2:-}"
}

PATHS=()
read_paths() {
  local x
  while IFS= read -r x; do
    valid_path "$x" || die "invalid path '$x'"
    PATHS+=("$(norm "$x")")
  done < <(jq -r '.paths[]?' <<<"$P")
  [ "${#PATHS[@]}" -gt 0 ] || die "paths is required"
}

run_restic() { # label args... ; stdout -> $W/out, stderr last line reported 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
}

# validate before touching the network
case "$MODE" in
  files-to-path)
    read_paths
    # Source paths only select from the snapshot; everything lands under a fresh, empty targetDir in
    # $TBASE, so a protected source path (e.g. /root/.gnupg) is safe to copy out and is not refused here.
    TARGET=$(jq -r '.targetDir // empty' <<<"$P")
    [[ "$TARGET" =~ ^"$TBASE"/[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*$ ]] || die "targetDir must be under $TBASE/"
    [[ "$TARGET/" != *"/../"* && "$TARGET/" != *"/./"* ]] || die "targetDir must not contain . or .. components"
    case "$(realpath -m -- "$TARGET")" in "$(realpath -m -- "$TBASE")"/*) ;; *) die "targetDir resolves outside $TBASE/";; esac
    if [ -e "$TARGET" ] || [ -L "$TARGET" ]; then
      [ -d "$TARGET" ] && [ ! -L "$TARGET" ] || die "targetDir exists and is not a directory"
      [ -z "$(ls -A "$TARGET")" ] || die "targetDir exists and is not empty"
    fi
    ;;
  files-in-place)
    jq -e '.overwrite == true' <<<"$P" >/dev/null 2>&1 || die "overwrite: true is required for files-in-place"
    read_paths
    for x in "${PATHS[@]}"; do
      if is_protected_any "$x" allow; then die "refusing to restore in place over protected path $x"; fi
    done
    ;;
  postgres-container)
    NAME=$(jq -r '.name // empty' <<<"$P"); C=$(jq -r '.container // empty' <<<"$P")
    DB=$(jq -r '.database // empty' <<<"$P"); U=$(jq -r '.dbUser // empty' <<<"$P")
    [[ "$NAME" =~ $NAME_RE ]] || die "invalid piece name"
    [[ "$C" =~ ^[A-Za-z0-9_.-]+$ && "$DB" =~ ^[A-Za-z0-9_.-]+$ && "$U" =~ ^[A-Za-z0-9_.-]+$ ]] || die "invalid container/database/dbUser"
    ;;
  *) die "mode must be files-to-path, files-in-place or postgres-container";;
esac

# in place: a symlink already inside the target tree must not lead outside it (restic would write through it)
if [ "$MODE" = files-in-place ]; then
  for x in "${PATHS[@]}"; do
    root="${RROOT%/}$x"
    [ -d "$root" ] || continue
    rr=$(realpath -m -- "$root")
    while IFS= read -r l; do
      case "$(realpath -m -- "$l")" in "$rr"|"$rr"/*) ;; *) die "refusing: $l is a symlink leading outside $x";; esac
    done < <(find "$root" -type l)
  done
fi

backup_reachable

# Verify per snapshot entry (restic restore never deletes extras, so counting files on disk would lie):
# every type==file entry from `restic ls` must exist under $1 with the same size, and every requested
# path must be a node of the snapshot. One pass: the disk listing is joined against the snapshot listing in awk.
# sets EXPECTED (files in the snapshot under the paths), RESTORED (matching on disk), BYTES, MISSING (first absent path).
verify_entries() { # dest path...
  local dest="${1%/}" p; shift
  run_restic ls ls --recursive --json "$SNAP" "$@"
  jq -r 'select(.type=="file") | "\(.path)\t\(.size // 0)"' "$W/out" > "$W/exp.tsv"
  jq -r '.path // empty' "$W/out" > "$W/nodes.txt"
  MISSING=""
  for p in "$@"; do
    if ! grep -qxF -- "$p" "$W/nodes.txt"; then MISSING="$p"; break; fi
  done
  : > "$W/disk.tsv"
  for p in "$@"; do
    if [ -e "$dest$p" ]; then find "$dest$p" -type f -printf '%p\t%s\n' >> "$W/disk.tsv"; fi
  done
  read -r EXPECTED RESTORED BYTES < <(awk -F'\t' -v d="$dest" '
    NR==FNR { disk[$1] = $2; next }
    { e++; if ((d $1) in disk && disk[d $1] == $2) { r++; b += $2 } }
    END { print e+0, r+0, b+0 }' "$W/disk.tsv" "$W/exp.tsv")
}

case "$MODE" in
  files-to-path|files-in-place)
    inc=(); roots=()
    for p in "${PATHS[@]}"; do inc+=(--include "$p"); done
    if [ "$MODE" = files-to-path ]; then
      if [ ! -e "$TARGET" ]; then install -d -m 0700 "$TARGET"; fi
      dest="$TARGET"
    else
      dest="$RROOT"
    fi
    for p in "${PATHS[@]}"; do roots+=("${dest%/}$p"); done
    echo "== restore $SNAP -> $dest"
    run_restic restore restore "$SNAP" --target "$dest" "${inc[@]}" --verify
    verify_entries "$dest" "${PATHS[@]}"
    verified=true
    if [ -n "$MISSING" ]; then verified=false; echo "path not in snapshot: $MISSING" >&2; fi
    if [ "$EXPECTED" -eq 0 ]; then verified=false; echo "restore: snapshot has no files under the requested paths" >&2; fi
    if [ "$RESTORED" -ne "$EXPECTED" ]; then verified=false; fi
    rj=$(printf '%s\n' "${roots[@]}" | jq -R . | jq -sc .)
    jq -n --arg s "$SNAP" --arg m "$MODE" --argjson f "$RESTORED" --argjson e "$EXPECTED" --argjson b "$BYTES" --argjson v "$verified" --argjson r "$rj" \
      '{snapshotId:$s,mode:$m,filesExpected:$e,filesRestored:$f,bytesRestored:$b,verified:$v,restoredRoots:$r}' > "$SSR_OUTPUTS"
    if [ "$verified" != true ]; then echo "restore: restored $RESTORED of $EXPECTED files" >&2; exit 2; fi
    ;;
  postgres-container)
    DUMP="$BACKUP_STATE_DIR/stage/$PLAN/$NAME.dump"
    rm -rf "$SCRATCH"; mkdir -p "$SCRATCH"; chmod 0700 "$SCRATCH"
    [ "$(docker inspect -f '{{.State.Running}}' "$C" 2>/dev/null || true)" = true ] || die "container $C not running"
    echo "== restore dump $SNAP"
    run_restic restore restore "$SNAP" --target "$SCRATCH" --include "$DUMP" --verify
    verify_entries "$SCRATCH" "$DUMP"
    if [ "$RESTORED" -ne 1 ] || [ "$EXPECTED" -ne 1 ] || [ -n "$MISSING" ]; then
      jq -n --arg s "$SNAP" --arg m "$MODE" --argjson e "$EXPECTED" --argjson f "$RESTORED" \
        '{snapshotId:$s,mode:$m,filesExpected:$e,filesRestored:$f,bytesRestored:0,verified:false}' > "$SSR_OUTPUTS"
      echo "restore: dump $DUMP missing or mismatched (restored $RESTORED of $EXPECTED)" >&2; exit 2
    fi
    F="$SCRATCH$DUMP"; bytes="$BYTES"
    echo "== pg_restore into $C/$DB"
    rc=0
    docker exec -i "$C" pg_restore -U "$U" -d "$DB" --clean --if-exists --no-owner < "$F" > "$W/pg.out" 2> "$W/pg.err" || rc=$?
    if grep -q '^pg_restore: error:' "$W/pg.err" "$W/pg.out"; then
      echo "pg_restore failed: $(grep -h '^pg_restore: error:' "$W/pg.err" "$W/pg.out" | head -n 1)" >&2; exit 1
    fi
    if [ "$rc" -ne 0 ]; then
      # Real pg_restore (>= 12) prints a "pg_restore: error:" line for every error it counts, so a non-zero exit
      # normally ends above: any real error fails the restore, which is strict and intended. Only an exit 1 that
      # carries the warnings marker WITHOUT any error line is tolerated here.
      if [ "$rc" -eq 1 ] && grep -q 'pg_restore: warning: errors ignored on restore' "$W/pg.err"; then
        echo "pg_restore finished with ignored warnings"
      else
        echo "pg_restore failed (exit $rc): $(backup_last_line "$W/pg.err")" >&2; exit "$rc"
      fi
    fi
    tables=$(docker exec "$C" psql -U "$U" -d "$DB" -Atc "select count(*) from information_schema.tables where table_schema='public'" 2>/dev/null | tr -d '[:space:]' || true)
    [[ "$tables" =~ ^[0-9]+$ ]] || die "could not count tables in $DB"
    jq -n --arg s "$SNAP" --arg m "$MODE" --argjson b "$bytes" --arg d "$DB" --argjson t "$tables" \
      '{snapshotId:$s,mode:$m,filesExpected:1,filesRestored:1,bytesRestored:$b,verified:true,database:$d,publicTables:$t}' > "$SSR_OUTPUTS"
    ;;
esac
echo "restore ok"
