#!/bin/bash
# Script to find particle-os VM's current IP and update SSH config

echo "🔍 Finding particle-os VM..."

# Method 1: Try to ping the current known IP
if ping -c 1 -W 1 192.168.122.77 &>/dev/null; then
    CURRENT_IP="192.168.122.77"
    echo "✅ Found particle-os at current IP: $CURRENT_IP"
else
    echo "❌ Current IP 192.168.122.77 not responding"
    
    # Method 2: Scan the common libvirt subnet
    echo "🔍 Scanning 192.168.122.x subnet..."
    for i in {1..254}; do
        ip="192.168.122.$i"
        if ping -c 1 -W 1 "$ip" &>/dev/null; then
            # Try to SSH and check hostname
            if timeout 5 ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null joe@"$ip" "hostname" 2>/dev/null | grep -q "particle-os"; then
                CURRENT_IP="$ip"
                echo "✅ Found particle-os at new IP: $CURRENT_IP"
                break
            fi
        fi
    done
fi

if [ -z "$CURRENT_IP" ]; then
    echo "❌ Could not find particle-os VM"
    echo "💡 Make sure the VM is running and accessible"
    exit 1
fi

# Update SSH config
echo "📝 Updating SSH config..."
cp ~/.ssh/config ~/.ssh/config.backup

# Remove old particle-os entries and add new ones
grep -v -A 6 "Host particle-os$" ~/.ssh/config.backup > ~/.ssh/config.tmp
grep -v -A 6 "Host particle-os-local$" ~/.ssh/config.tmp > ~/.ssh/config

# Add updated config
cat >> ~/.ssh/config << EOF

# particle-os VM configuration (auto-updated $(date))
Host particle-os
    HostName $CURRENT_IP
    User joe
    Port 22
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
    LogLevel QUIET

Host particle-os-local
    HostName particle-os.local
    User joe
    Port 22
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
    LogLevel QUIET
EOF

rm ~/.ssh/config.tmp

echo "✅ SSH config updated!"
echo "🚀 You can now use: ssh particle-os"
echo "💡 Current particle-os IP: $CURRENT_IP"

# Test the connection
echo "🧪 Testing connection..."
if ssh particle-os "echo 'Connection test successful!'" 2>/dev/null; then
    echo "✅ SSH connection working!"
else
    echo "❌ SSH connection failed"
fi
