#!/usr/bin/env bash
# backup-memory.sh — backs up the ormah memory directory with a timestamp tag

set -euo pipefail

MEMORY_DIR="${ORMAH_MEMORY_DIR:-$HOME/.local/share/ormah/memory}"
BACKUP_DIR="${ORMAH_BACKUP_DIR:-$HOME/.local/share/ormah-backups}"
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
DEST="$BACKUP_DIR/memory_$TIMESTAMP"

if [ ! -d "$MEMORY_DIR" ]; then
  echo "Error: memory directory not found at $MEMORY_DIR" >&2
  exit 1
fi

mkdir -p "$BACKUP_DIR"
cp -r "$MEMORY_DIR" "$DEST"

echo "Backed up to: $DEST"

# Keep only the 10 most recent backups
BACKUP_COUNT=$(ls -1d "$BACKUP_DIR"/memory_* 2>/dev/null | wc -l)
if [ "$BACKUP_COUNT" -gt 10 ]; then
  ls -1dt "$BACKUP_DIR"/memory_* | tail -n +"$((10 + 1))" | xargs rm -rf
  echo "Pruned old backups (kept 10 most recent)"
fi
