#!/usr/bin/env bash
# Restores a Storage Agent object backup produced by backup-storage.sh —
# runs on the Raspberry Pi. See docs/PROJECT_PLAN.md §0B.23: storage is
# restored *after* the database, and a reconciliation scan
# (app:reconcile-storage, run from the VPS) should follow before opening
# the service to users.
#
# Usage: ./restore-storage.sh <backup-file.tar.gz>
#        ./restore-storage.sh --latest [backup-dir]
#
# DESTRUCTIVE: replaces the contents of the live object directory. The
# current contents are moved aside (not deleted) first, as a safety net —
# see the "moved aside" path printed at the end. Requires explicit
# confirmation unless CONFIRM=yes is set in the environment (for scripted
# disaster-recovery drills).
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"

source "$script_dir/lib/env.sh"

if [[ "${1:-}" == "--latest" ]]; then
  backup_dir="${2:-$repo_root/backups/storage}"
  backup_file="$(find "$backup_dir" -maxdepth 1 -name 'storage-*.tar.gz' -type f | sort -r | head -n1)"
  if [[ -z "$backup_file" ]]; then
    echo "error: no storage-*.tar.gz backups found in $backup_dir" >&2
    exit 1
  fi
else
  backup_file="${1:?Usage: $0 <backup-file.tar.gz> | --latest [backup-dir]}"
fi

if [[ ! -f "$backup_file" ]]; then
  echo "error: $backup_file does not exist" >&2
  exit 1
fi

if [[ ! -f "$repo_root/pi.env" ]]; then
  echo "error: $repo_root/pi.env not found — run this from a real Pi deployment, not a dev checkout" >&2
  exit 1
fi

data_path="$(env_var "$repo_root/pi.env" STORAGE_AGENT_DATA_PATH)"
: "${data_path:?STORAGE_AGENT_DATA_PATH not set in pi.env}"

echo "About to restore $backup_file into $data_path."
echo "The Storage Agent should be stopped first (docker compose -f docker-compose.pi.yml stop storage-agent)."
echo "Current contents of $data_path will be moved aside, not deleted."
if [[ "${CONFIRM:-}" != "yes" ]]; then
  read -r -p "Type RESTORE to confirm: " typed
  if [[ "$typed" != "RESTORE" ]]; then
    echo "Aborted: confirmation did not match." >&2
    exit 1
  fi
fi

if [[ -d "$data_path" ]]; then
  moved_aside="${data_path}.pre-restore-$(date +%Y%m%d-%H%M%S)"
  mv "$data_path" "$moved_aside"
  echo "Moved existing contents aside to $moved_aside"
fi

mkdir -p "$(dirname "$data_path")"
tar -xzf "$backup_file" -C "$(dirname "$data_path")"

echo "Storage restored from $backup_file into $data_path."
echo "Next: restart the Storage Agent, then from the VPS run"
echo "  docker compose exec backend php artisan app:reconcile-storage"
echo "before opening the service to users — see PROJECT_PLAN.md §0B.23."
