#!/usr/bin/env bash
# Restore the shared database from the git-tracked backup.
# Use after cloning or when the shared database is missing.
# Called via `make db-install`.
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"

if [ -f "$DB_PATH" ]; then
    echo "error: shared database already exists at $DB_PATH" >&2
    echo "       delete it first if you want to restore from backup" >&2
    exit 1
fi

if [ ! -f "$BACKUP_PATH" ]; then
    echo "error: backup not found at $BACKUP_PATH" >&2
    echo "       run 'make db-backup' on the main branch first" >&2
    exit 1
fi

cp "$BACKUP_PATH" "$DB_PATH"
echo "ok: restored $(du -h "$DB_PATH" | cut -f1) to $DB_PATH"
