#!/bin/bash

echo "🔍 Simple Vaultwarden Migration Check"
echo "===================================="

# Test 1: SSH connectivity
echo "Test 1: SSH connectivity to lenovo410"
if ssh jonathan@192.168.50.181 "echo 'SSH works'" 2>/dev/null; then
    echo "✅ SSH connection successful"
else
    echo "❌ SSH connection failed"
    exit 1
fi

# Test 2: Vaultwarden container status
echo "Test 2: Vaultwarden container status"
if ssh jonathan@192.168.50.181 "docker ps | grep vaultwarden" 2>/dev/null; then
    echo "✅ Vaultwarden container is running"
else
    echo "❌ Vaultwarden container not found"
    exit 1
fi

# Test 3: Data directory
echo "Test 3: Data directory check"
if ssh jonathan@192.168.50.181 "[ -d '/home/jonathan/vaultwarden/data' ]" 2>/dev/null; then
    echo "✅ Data directory exists"
    
    # Check for critical files
    if ssh jonathan@192.168.50.181 "[ -f '/home/jonathan/vaultwarden/data/db.sqlite3' ]" 2>/dev/null; then
        echo "✅ SQLite database exists"
    else
        echo "❌ SQLite database not found"
        exit 1
    fi
else
    echo "❌ Data directory not found"
    exit 1
fi

# Test 4: NFS mount
echo "Test 4: NFS mount check"
if ssh jonathan@192.168.50.181 "[ -d '/mnt/vaultwarden' ]" 2>/dev/null; then
    echo "✅ NFS vaultwarden directory exists on lenovo410"
    
    # Test write access
    if ssh jonathan@192.168.50.181 "touch /mnt/vaultwarden/test_write && rm -f /mnt/vaultwarden/test_write" 2>/dev/null; then
        echo "✅ Write access to NFS directory"
    else
        echo "❌ Cannot write to NFS directory"
        exit 1
    fi
else
    echo "❌ NFS vaultwarden directory not found on lenovo410"
    exit 1
fi

# Test 5: Docker Swarm
echo "Test 5: Docker Swarm check"
if docker node ls >/dev/null 2>&1; then
    echo "✅ Docker Swarm manager access"
else
    echo "❌ Not on Docker Swarm manager"
    exit 1
fi

# Test 6: Create backup
echo "Test 6: Creating backup"
mkdir -p ./backups/vaultwarden
BACKUP_FILE="./backups/vaultwarden/test_backup_$(date +%Y%m%d_%H%M%S).tar.gz"

if ssh jonathan@192.168.50.181 "tar czf - -C /home/jonathan/vaultwarden/data ." > "$BACKUP_FILE" 2>/dev/null; then
    BACKUP_SIZE=$(stat -c%s "$BACKUP_FILE" 2>/dev/null || echo "0")
    echo "✅ Backup created: $BACKUP_FILE (${BACKUP_SIZE} bytes)"
    
    if [ "$BACKUP_SIZE" -gt 1000000 ]; then
        echo "✅ Backup size is reasonable"
    else
        echo "⚠️  Backup seems small"
    fi
else
    echo "❌ Backup creation failed"
    exit 1
fi

echo ""
echo "🎉 All tests passed! Vaultwarden migration is ready."
echo ""
echo "Next steps:"
echo "1. Run: ./scripts/migrate_vaultwarden_sqlite.sh"
echo "2. Test the new service for 24 hours"
echo "3. Stop the old service if everything works correctly"
