#!/usr/bin/env bash
# Copy the shared database into git-tracked docs/backups/ for disaster recovery.
# Only runs on the main branch — called via `make db-backup`.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WORKTREE_ROOT="$(dirname "$SCRIPT_DIR")"
DB_PATH="$(dirname "$WORKTREE_ROOT")/settledreach.db"
BACKUP_PATH="$WORKTREE_ROOT/docs/backups/settledreach.db.backup"

branch="$(git -C "$WORKTREE_ROOT" branch --show-current)"
if [ "$branch" != "main" ]; then
    echo "error: db-backup only runs on the main branch (currently on '$branch')" >&2
    exit 1
fi

if [ ! -f "$DB_PATH" ]; then
    echo "error: shared database not found at $DB_PATH" >&2
    exit 1
fi

cp "$DB_PATH" "$BACKUP_PATH"
echo "ok: backed up $(du -h "$BACKUP_PATH" | cut -f1) to docs/backups/settledreach.db.backup"
