#!/bin/bash
#
# Studio EinsZwoVier - Production Migration Script
# Run this FROM the dev Mac (einszwovier.local) to migrate to production Mac (124.local)
#

# Don't exit on error - we'll handle retries
set +e

echo "════════════════════════════════════════════════════════════════"
echo "   Studio EinsZwoVier - Production Migration Script"
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "This will copy the entire webapp from THIS machine to admin@124.local"
echo ""
echo "Prerequisites:"
echo "  - You're running this ON the dev Mac (einszwovier.local)"
echo "  - You have SSH access to 124.local (configured as 'ssh 124')"
echo "  - Docker Desktop is installed on production Mac (124.local)"
echo ""

read -p "Ready to proceed? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Migration cancelled."
    exit 1
fi

# Variables
PROD_MAC="124"  # SSH config alias for admin@124.local
DEV_PATH="/Users/aron124/webapp_124"
PROD_PATH="/Users/admin/webapp_124"
MAX_RETRIES=5

echo ""
echo "═══ Step 1: Stop services on dev Mac (locally) ═══"
cd "$DEV_PATH"
docker compose down
echo "✅ Services stopped"

echo ""
echo "═══ Step 2: Create directory structure on production Mac ═══"
ssh "$PROD_MAC" "mkdir -p $(dirname "$PROD_PATH")"
echo "✅ Directory created"

echo ""
echo "═══ Step 3: Copy all files (auto-resume enabled) ═══"
echo "Copying from: $DEV_PATH (local)"
echo "Copying to:   $PROD_MAC:$PROD_PATH"
echo ""

# Rsync with auto-retry on failure
RETRY_COUNT=0
RSYNC_SUCCESS=0

while [ $RETRY_COUNT -lt $MAX_RETRIES ] && [ $RSYNC_SUCCESS -eq 0 ]; do
    if [ $RETRY_COUNT -gt 0 ]; then
        echo ""
        echo "⚠️  Connection interrupted. Resuming transfer (attempt $((RETRY_COUNT + 1))/$MAX_RETRIES)..."
        sleep 5
    fi

    if command -v rsync &> /dev/null; then
        # Rsync with:
        # -a: archive mode
        # -v: verbose
        # --progress: show progress
        # --partial: keep partially transferred files
        # --append-verify: resume from where we left off
        # --timeout=300: 5min timeout per operation
        # --compress-level=0: no compression (faster for local network)
        rsync -av --progress --partial --append-verify --timeout=300 --compress-level=0 \
              --no-inc-recursive "$DEV_PATH/" "$PROD_MAC:$PROD_PATH/"

        if [ $? -eq 0 ]; then
            RSYNC_SUCCESS=1
        else
            RETRY_COUNT=$((RETRY_COUNT + 1))
        fi
    else
        # Fallback to scp with keep-alive
        scp -o ServerAliveInterval=60 -o ServerAliveCountMax=10 -r "$DEV_PATH" "$PROD_MAC:$(dirname "$PROD_PATH")/"

        if [ $? -eq 0 ]; then
            RSYNC_SUCCESS=1
        else
            RETRY_COUNT=$((RETRY_COUNT + 1))
        fi
    fi
done

if [ $RSYNC_SUCCESS -eq 0 ]; then
    echo ""
    echo "❌ Failed to transfer files after $MAX_RETRIES attempts."
    echo "You can manually resume with:"
    echo "  rsync -av --progress --partial --append-verify $DEV_PATH/ $PROD_MAC:$PROD_PATH/"
    exit 1
fi

echo "✅ Files copied successfully"

echo ""
echo "═══ Step 4: Fix file permissions on production Mac ═══"
ssh "$PROD_MAC" "sudo chown -R \$(whoami):staff '$PROD_PATH' && chmod -R 755 '$PROD_PATH/matrix' '$PROD_PATH/ollama' '$PROD_PATH/open-webui' '$PROD_PATH/bookstack' '$PROD_PATH/docmost' '$PROD_PATH/data' 2>/dev/null || true"
echo "✅ Permissions fixed"

echo ""
echo "═══ Step 5: Start services on production Mac ═══"
ssh "$PROD_MAC" "cd '$PROD_PATH' && docker compose up -d"

echo "✅ Services starting..."
echo ""
echo "Waiting 30 seconds for services to initialize..."
sleep 30

echo ""
echo "═══ Step 6: Check service status ═══"
ssh "$PROD_MAC" "cd '$PROD_PATH' && docker compose ps"

echo ""
echo "════════════════════════════════════════════════════════════════"
echo "   Migration Complete!"
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "Next steps:"
echo "  1. Verify services are healthy: ssh 124 'cd /Users/admin/webapp_124 && docker compose ps'"
echo "  2. Check logs if issues: ssh 124 'cd /Users/admin/webapp_124 && docker compose logs [service-name]'"
echo "  3. Test web interface: http://124.local"
echo "  4. Test cost calculator with a PDF upload"
echo "  5. Verify Matrix integration works"
echo ""
echo "To restart dev Mac services (this machine):"
echo "  cd $DEV_PATH && docker compose up -d"
echo ""
echo "Full migration guide: $DEV_PATH/MIGRATION.md"
echo "════════════════════════════════════════════════════════════════"
