#!/bin/sh
# Snapshot the canonical SQLite DB into data/backups/, keeping the last 14.
# Uses sqlite3 .backup (safe against a live WAL). Run from the project root,
# e.g. weekly via launchd/cron, or by hand before risky migrations.
set -eu
cd "$(dirname "$0")/.."

DB=data/garmin.db
OUT=data/backups/garmin-$(date +%Y%m%d-%H%M%S).db

mkdir -p data/backups
sqlite3 "$DB" ".backup $OUT"
echo "backed up $DB -> $OUT"

# prune: keep newest 14 dated snapshots
ls -1t data/backups/garmin-*.db 2>/dev/null | tail -n +15 | while read -r f; do
  rm -- "$f"
  echo "pruned $f"
done
