#!/bin/bash
# IP Conflict Investigation Script for 192.168.11.14

IP="192.168.11.14"
echo "=== Investigating IP: $IP ==="
echo ""

# Step 1: Ping test
echo "1. Testing connectivity..."
if ping -c 2 -W 2 $IP > /dev/null 2>&1; then
    echo "   ✅ Device is reachable"
else
    echo "   ❌ Device is NOT reachable"
    exit 1
fi

# Step 2: ARP lookup
echo ""
echo "2. Checking ARP table..."
MAC=$(arp -n $IP 2>/dev/null | awk '{print $3}' | grep -E '^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$')
if [ -n "$MAC" ]; then
    echo "   ✅ MAC Address: $MAC"
    echo "   Checking MAC vendor..."
    # Extract first 6 characters (OUI)
    OUI=$(echo $MAC | tr '[:lower:]' '[:upper:]' | sed 's/[:-]//g' | cut -c1-6)
    echo "   OUI: $OUI"
else
    echo "   ⚠️  No ARP entry found (unusual)"
    echo "   Trying alternative method..."
    MAC=$(ip neigh show $IP 2>/dev/null | awk '{print $5}')
    if [ -n "$MAC" ]; then
        echo "   ✅ MAC Address (from ip neigh): $MAC"
    else
        echo "   ❌ Could not determine MAC address"
    fi
fi

# Step 3: SSH banner check
echo ""
echo "3. Checking SSH service..."
SSH_BANNER=$(timeout 3 ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no root@$IP "echo 'Connected'" 2>&1 | grep -i "ubuntu\|debian\|openssh" | head -1)
if [ -n "$SSH_BANNER" ]; then
    echo "   SSH Info: $SSH_BANNER"
else
    SSH_TEST=$(timeout 3 ssh -o ConnectTimeout=2 -o StrictHostKeyChecking=no root@$IP 2>&1 | head -5)
    echo "   SSH Response:"
    echo "$SSH_TEST" | head -3
fi

# Step 4: Port scan
echo ""
echo "4. Checking open ports..."
for port in 22 80 443 8006; do
    if timeout 2 nc -zv -w 1 $IP $port > /dev/null 2>&1; then
        echo "   ✅ Port $port: OPEN"
    else
        echo "   ❌ Port $port: CLOSED"
    fi
done

# Step 5: Check Proxmox hosts
echo ""
echo "5. Checking Proxmox cluster for this IP..."
for host in 192.168.11.10 192.168.11.11 192.168.11.12; do
    echo "   Checking $host..."
    ssh -o ConnectTimeout=3 root@$host "pct list 2>/dev/null | grep -E 'VMID|$IP' || qm list 2>/dev/null | grep -E 'VMID|$IP'" 2>/dev/null | head -5
done

echo ""
echo "=== Investigation Complete ==="
