#!/usr/bin/env bash
#
# Disaster-recovery restore for the self-hosted VPS. Companion to
# scripts/backup-offsite.sh. Proves the backups are actually restorable —
# an untested backup is a hope, not a backup.
#
# Usage:
#   scripts/restore.sh repos <repos-YYYYMMDD-HHMMSS.tar.gz> [--dest DIR]
#   scripts/restore.sh db    <db-YYYYMMDD-HHMMSS.dump> [--target-url URL]
#
# Modes:
#   repos  Extract a repos snapshot into --dest (default: a scratch dir under
#          /tmp so you can diff/verify before swapping it into place). It does
#          NOT overwrite the live $GIT_REPOS_PATH unless you point --dest there.
#   db     pg_restore a db dump into --target-url (default: $SCRATCH_DATABASE_URL,
#          NEVER $DATABASE_URL by default — restoring over prod must be explicit).
#
# Pull an artifact from offsite first if needed:
#   rclone copy $BACKUP_RCLONE_REMOTE/repos/repos-<ts>.tar.gz ./
set -euo pipefail

log() { echo "$(date -Is) [restore] $*"; }
die() { log "FATAL: $*"; exit 1; }

mode="${1:-}"; artifact="${2:-}"
shift 2 2>/dev/null || true

[ -n "$mode" ] && [ -n "$artifact" ] || die "usage: restore.sh {repos|db} <artifact> [opts]"
[ -f "$artifact" ] || die "artifact not found: $artifact"

case "$mode" in
  repos)
    dest="/tmp/gluecron-restore-$(date +%s)"
    while [ $# -gt 0 ]; do case "$1" in --dest) dest="$2"; shift 2;; *) shift;; esac; done
    mkdir -p "$dest"
    tar -xzf "$artifact" -C "$dest"
    log "extracted repos snapshot into: $dest"
    log "verify a repo, e.g.:  git -C \"$dest\"/repos/<owner>/<name>.git log -1"
    log "when satisfied, swap into place by stopping gluecron and rsync-ing over \$GIT_REPOS_PATH"
    ;;
  db)
    target="${SCRATCH_DATABASE_URL:-}"
    while [ $# -gt 0 ]; do case "$1" in --target-url) target="$2"; shift 2;; *) shift;; esac; done
    [ -n "$target" ] || die "no target: pass --target-url or set SCRATCH_DATABASE_URL (refusing to guess prod)"
    log "restoring $artifact into $target"
    pg_restore --clean --if-exists --no-owner --no-privileges --dbname "$target" "$artifact"
    log "restore complete. sanity-check:  psql \"$target\" -c 'select count(*) from users;'"
    ;;
  *)
    die "unknown mode '$mode' (want: repos | db)"
    ;;
esac
