#!/usr/bin/env bash
# Refresh seed/data/ from the live StartOS 0.3.5 host over SSH.
#
# Usage:
#   ./start9/0.4/refresh_seed.sh <ssh-target> [remote-volume-path]
#
# Example (most common):
#   ./start9/0.4/refresh_seed.sh embassy@embassy.local
#
# Example (custom remote path):
#   ./start9/0.4/refresh_seed.sh embassy@embassy.local \
#       /embassy-data/package-data/volumes/proof-of-work/data/main
#
# Behavior:
#   - Auto-detects /embassy-data/package-data/volumes/proof-of-work/data/main
#     if the remote path is omitted.
#   - Refuses to overwrite a non-empty seed/data/ without confirmation.
#   - After SCP, runs PRAGMA integrity_check and prints expected row counts.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SEED_DATA_DIR="${SCRIPT_DIR}/seed/data"

if [ "$#" -lt 1 ]; then
  echo "usage: $0 <ssh-target> [remote-volume-path]" >&2
  exit 64
fi

SSH_TARGET="$1"
REMOTE_PATH="${2:-/embassy-data/package-data/volumes/proof-of-work/data/main}"

echo "[refresh-seed] target:       ${SSH_TARGET}"
echo "[refresh-seed] remote path:  ${REMOTE_PATH}"
echo "[refresh-seed] local seed:   ${SEED_DATA_DIR}"

mkdir -p "${SEED_DATA_DIR}"

# Prompt if seed/data/ already has files.
if [ -n "$(ls -A "${SEED_DATA_DIR}" 2>/dev/null || true)" ]; then
  echo
  echo "[refresh-seed] WARNING: ${SEED_DATA_DIR} is non-empty:" >&2
  ls -la "${SEED_DATA_DIR}" >&2
  echo
  read -r -p "Overwrite existing seed? [y/N] " answer
  case "${answer:-N}" in
    y|Y|yes|YES) ;;
    *) echo "[refresh-seed] aborted."; exit 1 ;;
  esac
fi

# Verify the remote path exists before copying.
echo "[refresh-seed] verifying remote path exists..."
if ! ssh "${SSH_TARGET}" "test -d \"${REMOTE_PATH}\""; then
  echo "[refresh-seed] remote path not found on ${SSH_TARGET}:${REMOTE_PATH}" >&2
  exit 1
fi

# Copy everything under the volume root (preserves mode/time).
echo "[refresh-seed] copying volume contents via rsync..."
rsync -aP --delete-excluded --exclude='.seeded' \
  "${SSH_TARGET}:${REMOTE_PATH}/" \
  "${SEED_DATA_DIR}/"

# Integrity check on the primary SQLite file, if present.
DB_PATH="${SEED_DATA_DIR}/app.db"
if [ -f "${DB_PATH}" ]; then
  echo
  echo "[refresh-seed] sqlite integrity_check:"
  sqlite3 "${DB_PATH}" "PRAGMA integrity_check;" || {
    echo "[refresh-seed] WARNING: integrity_check failed" >&2
  }
  echo
  echo "[refresh-seed] row counts:"
  for t in User Workout Exercise SetLog UserPreferences Program Session; do
    n="$(sqlite3 "${DB_PATH}" "SELECT COUNT(*) FROM \"${t}\";" 2>/dev/null || echo '-')"
    printf '  %-18s %s\n' "${t}" "${n}"
  done
else
  echo "[refresh-seed] NOTE: no app.db present in remote snapshot \u2014 skipped integrity check." >&2
fi

echo
echo "[refresh-seed] done. Review ${SEED_DATA_DIR}, commit the snapshot, and rebuild:"
echo "  cd start9/0.4 && make clean && make"
