#!/bin/bash
#
# Migrate Data from Jupiter (172.16.3.20) to RMM (172.16.3.30)
# Migrates conversation contexts and any other data
#

set -e

echo "=========================================="
echo "ClaudeTools Data Migration"
echo "=========================================="
echo ""
echo "Source: Jupiter (172.16.3.20:3306) - Docker MariaDB"
echo "Target: RMM (172.16.3.30:3306) - Native MariaDB"
echo ""

# Database credentials
DB_USER="claudetools"
DB_PASS="CT_e8fcd5a3952030a79ed6debae6c954ed"
DB_NAME="claudetools"
SOURCE_HOST="172.16.3.20"
TARGET_HOST="172.16.3.30"

# Step 1: Export data from Jupiter
echo "[1/4] Exporting data from Jupiter (172.16.3.20)..."
echo ""

# Use PuTTY's plink instead of SSH
plink -batch guru@${SOURCE_HOST} "docker exec mariadb mysqldump \
  -u ${DB_USER} \
  -p${DB_PASS} \
  --no-create-info \
  --skip-add-drop-table \
  --insert-ignore \
  ${DB_NAME} > /tmp/claudetools_data.sql && \
  cat /tmp/claudetools_data.sql" > D:/ClaudeTools/temp_data_export.sql

EXPORT_SIZE=$(wc -l < D:/ClaudeTools/temp_data_export.sql)
echo "Exported ${EXPORT_SIZE} lines"
echo ""

# Step 2: Check what tables have data
echo "[2/4] Analyzing exported data..."
echo ""

grep "^INSERT INTO" D:/ClaudeTools/temp_data_export.sql | \
  sed 's/INSERT INTO `\([^`]*\)`.*/\1/' | \
  sort | uniq -c | \
  awk '{printf "  %-30s %s rows\n", $2, $1}'

echo ""

# Step 3: Copy to RMM server
echo "[3/4] Transferring to RMM server..."
echo ""

# Use PuTTY's pscp to copy file
pscp -batch D:/ClaudeTools/temp_data_export.sql guru@${TARGET_HOST}:/tmp/

echo "File transferred"
echo ""

# Step 4: Import into RMM database
echo "[4/4] Importing into RMM database..."
echo ""

plink -batch guru@${TARGET_HOST} "mysql \
  -u ${DB_USER} \
  -p${DB_PASS} \
  -D ${DB_NAME} < /tmp/claudetools_data.sql && \
  echo 'Import successful'"

echo ""

# Step 5: Verify
echo "=========================================="
echo "Verification"
echo "=========================================="
echo ""

plink -batch guru@${TARGET_HOST} "mysql \
  -u ${DB_USER} \
  -p${DB_PASS} \
  -D ${DB_NAME} \
  -e \"SELECT 'conversation_contexts' as table_name, COUNT(*) as records FROM conversation_contexts \
      UNION ALL SELECT 'credentials', COUNT(*) FROM credentials \
      UNION ALL SELECT 'clients', COUNT(*) FROM clients \
      UNION ALL SELECT 'machines', COUNT(*) FROM machines \
      UNION ALL SELECT 'sessions', COUNT(*) FROM sessions;\" 2>/dev/null"

echo ""
echo "=========================================="
echo "Data Migration Complete!"
echo "=========================================="
echo ""

# Cleanup
rm -f D:/ClaudeTools/temp_data_export.sql
plink -batch guru@${TARGET_HOST} "rm -f /tmp/claudetools_data.sql" 2>/dev/null || true

echo "Temporary files cleaned up"
echo ""
echo "Next steps:"
echo "  1. Verify data in database"
echo "  2. Test context recall via API"
echo "  3. Update any remaining references to 172.16.3.20"
echo ""
