#!/usr/bin/env bash
# Daily Storage Agent object backup — runs on the Raspberry Pi, not the
# VPS. See docs/PROJECT_PLAN.md §29 and §0B.22 (a storage-only backup is
# not a complete NAS backup either; pair this with backup-database.sh on
# the VPS).
#
# Reads STORAGE_AGENT_DATA_PATH from pi.env (the same variable
# docker-compose.pi.yml bind-mounts into the container) and tars it
# directly off the host filesystem — no need to go through the Storage
# Agent's own API, since the bind mount means the bytes are already
# ordinary files on this host.
#
# Usage: ./backup-storage.sh [backup-dir]
# Typical cron entry (as root, from the repo root on the Pi):
#   0 2 * * * cd /opt/private-cloud-nas && infrastructure/scripts/backup-storage.sh >> /var/log/nas-backup-storage.log 2>&1
set -euo pipefail

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../.." && pwd)"
backup_dir="${1:-$repo_root/backups/storage}"

source "$script_dir/lib/rotate-backups.sh"
source "$script_dir/lib/env.sh"

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}"

if [[ ! -d "$data_path" ]]; then
  echo "error: $data_path does not exist — nothing to back up" >&2
  exit 1
fi

mkdir -p "$backup_dir"
stamp="$(date +%Y%m%d-%H%M%S)"
out="$backup_dir/storage-$stamp.tar.gz"
tmp_out="$out.partial"

echo "Backing up $data_path to $out"

if ! tar -czf "$tmp_out" -C "$(dirname "$data_path")" "$(basename "$data_path")"; then
  echo "error: tar failed — leaving no partial backup behind" >&2
  rm -f "$tmp_out"
  exit 1
fi

if [[ ! -s "$tmp_out" ]]; then
  echo "error: backup output is empty — treating as a failed backup" >&2
  rm -f "$tmp_out"
  exit 1
fi

mv "$tmp_out" "$out"
echo "Wrote $out ($(du -h "$out" | cut -f1))"

rotate_backups "$backup_dir" "storage-*.tar.gz" 7 4 6

echo "Done. $(find "$backup_dir" -maxdepth 1 -name 'storage-*.tar.gz' -type f | wc -l | tr -d ' ') backup(s) retained."
