#!/usr/bin/env bash
# Export local project SQLite DB (+ uploads) for backup / Docker import.
#
# Usage:
#   ./scripts/local-db-export.sh
#   ./scripts/local-db-export.sh ./backups/my-backup
#
# Sources (local):
#   server/prisma/dev.db   (+ -wal / -shm if present)
#   server/uploads/
#
# Restore locally:
#   ./scripts/local-db-import.sh ./backups/casegambling-….tar.gz
# Restore into Docker (prod):
#   ./scripts/docker-db-import.sh ./backups/casegambling-….tar.gz
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

LOCAL_DB="${LOCAL_DB:-$ROOT/server/prisma/dev.db}"
LOCAL_UPLOADS="${LOCAL_UPLOADS:-$ROOT/server/uploads}"
STAMP="$(date +%Y%m%d-%H%M%S)"
OUT="${1:-$ROOT/backups/casegambling-$STAMP}"

if [[ ! -f "$LOCAL_DB" ]]; then
  echo "Error: local database not found: $LOCAL_DB" >&2
  echo "Tip: run the app once, or set LOCAL_DB=/path/to/dev.db" >&2
  exit 1
fi

mkdir -p "$OUT"

echo "==> Exporting local database → $OUT/dev.db"
echo "    source: $LOCAL_DB"

# Prefer a consistent SQLite snapshot when sqlite3 is available
if command -v sqlite3 >/dev/null 2>&1; then
  sqlite3 "$LOCAL_DB" ".backup '$OUT/dev.db'"
  cp -f "$OUT/dev.db" "$OUT/prod.db"
else
  cp -f "$LOCAL_DB" "$OUT/dev.db"
  cp -f "$LOCAL_DB" "$OUT/prod.db"
  if [[ -f "${LOCAL_DB}-wal" ]]; then
    cp -f "${LOCAL_DB}-wal" "$OUT/dev.db-wal"
    cp -f "${LOCAL_DB}-wal" "$OUT/prod.db-wal"
  fi
  if [[ -f "${LOCAL_DB}-shm" ]]; then
    cp -f "${LOCAL_DB}-shm" "$OUT/dev.db-shm"
    cp -f "${LOCAL_DB}-shm" "$OUT/prod.db-shm"
  fi
fi

echo "==> Exporting local uploads → $OUT/uploads"
mkdir -p "$OUT/uploads"
if [[ -d "$LOCAL_UPLOADS" ]]; then
  cp -a "$LOCAL_UPLOADS"/. "$OUT/uploads/" 2>/dev/null || true
else
  echo "    (no uploads dir at $LOCAL_UPLOADS)"
fi

{
  echo "exported_at=$STAMP"
  echo "source=local"
  echo "local_db=$LOCAL_DB"
  echo "local_uploads=$LOCAL_UPLOADS"
  echo "database=dev.db"
  echo "uploads=uploads/"
} > "$OUT/manifest.txt"

TAR="$OUT.tar.gz"
tar -czf "$TAR" -C "$(dirname "$OUT")" "$(basename "$OUT")"

DB_SIZE="$(du -h "$OUT/dev.db" | awk '{print $1}')"
UPLOAD_COUNT="$(find "$OUT/uploads" -type f 2>/dev/null | wc -l | tr -d ' ')"

echo "==> Archive: $TAR"
echo "    db size: $DB_SIZE · uploads files: $UPLOAD_COUNT"
echo "==> Done."
echo "    Local restore:  ./scripts/local-db-import.sh $TAR"
echo "    Docker restore: ./scripts/docker-db-import.sh $TAR"
