#!/bin/bash
# ctg-standby-restore - restore ONE service dataset / CT rootfs / host path of the taken-over standby from the B2 restic repo.
#   ctg-standby-restore <name> <target-dir> [--snapshot ID] [--include SUBPATH ...] [--repo-dir DIR]
#   <name> = a dataset under ZFS_PARENT (forgejo, yes, plex, ...), ct<ID> (rootfs of CT <ID>, e.g. ct122) or an absolute host path (/etc/ctg-standby).
# The data lands directly in <target-dir> (e.g. a fresh ZFS dataset), numeric uids kept (run as root). To put a service back for real:
#   zfs create -o mountpoint=/rpool/standby/forgejo rpool/standby/forgejo; ctg-standby-restore forgejo /rpool/standby/forgejo
# Safety: takes the shared standby test lock, waits for a quiet pool, throttles the download (restore writes into ZFS cannot be capped
# by cgroups on this host's DRAM-less NVMe, the download rate is the limit), refuses a non-empty target, never touches live datasets.
set -uo pipefail
CONF=${CTG_BACKUP_CONF:-/etc/ctg-backup-standby}
ETC_STANDBY=${CTG_STANDBY_ETC:-/etc/ctg-standby}
[ -r "$ETC_STANDBY/standby.conf" ] && . "$ETC_STANDBY/standby.conf"
. "$CONF/standby.conf"
usage() { sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
[ $# -ge 2 ] || usage
NAME=$1; TARGET=$2; shift 2
SNAPID=latest; INCL=(); REPO_DIR=
while [ $# -gt 0 ]; do
  case $1 in
    --snapshot) SNAPID=$2; shift 2 ;;
    --include) INCL+=("$2"); shift 2 ;;
    --repo-dir) REPO_DIR=$2; shift 2 ;;   # test only: a local restic repo with the same layout
    *) usage ;;
  esac
done
set -a; . "$CONF/env"; set +a
[ -n "$REPO_DIR" ] && export RESTIC_REPOSITORY=$REPO_DIR
export HOME=${HOME:-/root}
[ -d "$TARGET" ] || { echo "target $TARGET does not exist (create the dataset first)" >&2; exit 2; }
[ -z "$(ls -A "$TARGET")" ] || { echo "target $TARGET is not empty: refusing" >&2; exit 2; }
case $NAME in
  /*) SRC=$NAME ;;
  ct[0-9]*) id=${NAME#ct}; vol=$(pct config "$id" | sed -n 's/^rootfs: \([^,]*\),.*/\1/p'); SRC=$(pvesm path "$vol")/.zfs/snapshot/$BACKUP_SNAPSHOT ;;
  *) SRC=$(zfs get -H -o value mountpoint "$ZFS_PARENT/$NAME")/.zfs/snapshot/$BACKUP_SNAPSHOT ;;
esac
echo "restoring $SRC from snapshot $SNAPID into $TARGET"
exec 9>"$TEST_LOCK"; flock -w 600 9 || { echo "standby test lock busy" >&2; exit 4; }
waited=0
while :; do
  p=$(sed -n 's/^full avg10=\([0-9]*\).*/\1/p' /proc/pressure/io); p=${p:-0}
  [ "$p" -lt "$BACKUP_PRESSURE_MAX" ] && break
  [ $waited -ge 270 ] && { echo "io pressure ${p}% >= $BACKUP_PRESSURE_MAX after 270 s: try again later" >&2; exit 5; }
  sleep 15; waited=$((waited+15))
done
TMP=$TARGET/.ctg-restore.$$
inc=()
if [ ${#INCL[@]} -gt 0 ]; then for i in "${INCL[@]}"; do inc+=(--include "$SRC/${i#/}"); done; else inc+=(--include "$SRC"); fi
ionice -c3 nice -n19 restic restore "$SNAPID" --tag ctg-daily --limit-download "$RESTORE_LIMIT_DOWNLOAD_KBPS" "${inc[@]}" --target "$TMP" || exit $?
# restic keeps the absolute snapshot path; hoist its content (same filesystem: renames, no data copy)
shopt -s dotglob nullglob
mv "$TMP$SRC"/* "$TARGET"/ && rm -rf "$TMP"
echo "restored into $TARGET: $(du -sh "$TARGET" | cut -f1)"
