#!/bin/bash
# Sync local TIP changes to Erik VPS
# Usage: ./scripts/sync-to-erik.sh

set -e

ERIK="root@82.165.222.127"
REMOTE_PATH="/opt/tip"
LOCAL_PATH="$(cd "$(dirname "$0")/.." && pwd)"

echo "=== TIP Sync to Erik ==="
echo "Local:  $LOCAL_PATH"
echo "Remote: $ERIK:$REMOTE_PATH"

# Test connection
echo ""
echo "[1/5] Testing SSH connection..."
ssh -o ConnectTimeout=5 "$ERIK" "echo 'Erik is online'" || { echo "ERROR: Erik unreachable"; exit 1; }

# Sync API source
echo ""
echo "[2/5] Syncing API source..."
rsync -avz --delete \
  "$LOCAL_PATH/packages/api/src/" \
  "$ERIK:$REMOTE_PATH/packages/api/src/"

# Sync Dashboard
echo ""
echo "[3/5] Syncing Dashboard..."
rsync -avz \
  "$LOCAL_PATH/packages/dashboard/index.html" \
  "$ERIK:$REMOTE_PATH/packages/dashboard/index.html"

# Sync MCP Server + Scraper source
echo ""
echo "[4/5] Syncing MCP Server + Scraper source..."
rsync -avz --delete \
  "$LOCAL_PATH/packages/mcp-server/src/" \
  "$ERIK:$REMOTE_PATH/packages/mcp-server/src/"

rsync -avz --delete \
  "$LOCAL_PATH/packages/scraper/src/" \
  "$ERIK:$REMOTE_PATH/packages/scraper/src/"

# Rebuild and restart
echo ""
echo "[5/5] Rebuilding and restarting on Erik..."
ssh "$ERIK" "\
  cd $REMOTE_PATH/packages/api     && npx tsc 2>&1 | tail -3; \
  cd $REMOTE_PATH/packages/scraper && npx tsc 2>&1 | tail -3; \
  pm2 restart tip-api 2>/dev/null; \
  pm2 restart tip-mcp 2>/dev/null; \
  pm2 restart tip-scraper-daemon 2>/dev/null; \
  echo 'Done. PM2 status:'; pm2 list 2>/dev/null | head -15"

echo ""
echo "=== Sync complete ==="
echo "Dashboard: https://transceiver-db.context-x.org/dashboard/"
echo "API:       https://transceiver-db.context-x.org/api/health"
