#!/bin/bash
# Complete VM 100 Guest Agent Verification and Fix
# Run on Proxmox node: root@ml110-01

set -euo pipefail

VMID=100

# Check if running on Proxmox node
if ! command -v qm &> /dev/null; then
    echo "=========================================="
    echo "ERROR: This script must be run on a Proxmox node"
    echo "=========================================="
    echo ""
    echo "The 'qm' command is not available on this machine."
    echo ""
    echo "This script must be run on the Proxmox node (root@ml110-01)"
    echo ""
    echo "To run this script:"
    echo "  1. SSH into the Proxmox node:"
    echo "     ssh root@ml110-01"
    echo ""
    echo "  2. Copy the script to the Proxmox node, or"
    echo ""
    echo "  3. Run commands directly on Proxmox node:"
    echo "     VMID=100"
    echo "     qm status \$VMID"
    echo "     qm config \$VMID | grep '^agent:'"
    echo "     qm guest exec \$VMID -- dpkg -l | grep qemu-guest-agent"
    echo ""
    exit 1
fi

echo "=========================================="
echo "Complete VM 100 Guest Agent Check & Fix"
echo "=========================================="
echo ""

# Step 1: Check VM status
echo "Step 1: Checking VM Status"
echo "--------------------------------------"
VM_STATUS=$(qm status $VMID | awk '{print $2}')
echo "VM Status: $VM_STATUS"

if [ "$VM_STATUS" != "running" ]; then
    echo "⚠️  VM is not running. Starting VM..."
    qm start $VMID
    echo "Waiting 30 seconds for VM to boot..."
    sleep 30
    VM_STATUS=$(qm status $VMID | awk '{print $2}')
    if [ "$VM_STATUS" != "running" ]; then
        echo "❌ VM failed to start"
        exit 1
    fi
fi
echo "✅ VM is running"
echo ""

# Step 2: Check Proxmox guest agent config
echo "Step 2: Checking Proxmox Guest Agent Configuration"
echo "--------------------------------------"
AGENT_CONFIG=$(qm config $VMID | grep '^agent:' || echo "")
if [ -z "$AGENT_CONFIG" ]; then
    echo "❌ Guest agent NOT configured in Proxmox"
    echo "Setting agent=1..."
    qm set $VMID --agent 1
    echo "✅ Guest agent configured"
else
    echo "✅ Guest agent configured: $AGENT_CONFIG"
fi
echo ""

# Step 3: Check if package is installed
echo "Step 3: Checking qemu-guest-agent Package Installation"
echo "--------------------------------------"
echo "Attempting to check via qm guest exec..."
echo ""

PACKAGE_CHECK=$(qm guest exec $VMID -- dpkg -l | grep qemu-guest-agent 2>&1)
EXEC_EXIT_CODE=$?

if [ $EXEC_EXIT_CODE -eq 0 ] && echo "$PACKAGE_CHECK" | grep -q "qemu-guest-agent"; then
    echo "✅ qemu-guest-agent package IS installed"
    echo ""
    echo "Package details:"
    echo "$PACKAGE_CHECK" | grep qemu-guest-agent
    echo ""
    
    # Step 4: Check service status
    echo "Step 4: Checking Service Status"
    echo "--------------------------------------"
    SERVICE_STATUS=$(qm guest exec $VMID -- systemctl status qemu-guest-agent --no-pager 2>&1)
    if echo "$SERVICE_STATUS" | grep -q "active (running)"; then
        echo "✅ qemu-guest-agent service IS running"
        echo ""
        echo "Service status:"
        echo "$SERVICE_STATUS" | head -10
        echo ""
        echo "=========================================="
        echo "✅ SUCCESS: Guest Agent is fully configured and running"
        echo "=========================================="
        exit 0
    elif echo "$SERVICE_STATUS" | grep -q "inactive"; then
        echo "⚠️  qemu-guest-agent service is installed but NOT running"
        echo "Attempting to start..."
        qm guest exec $VMID -- systemctl enable --now qemu-guest-agent
        sleep 3
        SERVICE_STATUS=$(qm guest exec $VMID -- systemctl status qemu-guest-agent --no-pager 2>&1)
        if echo "$SERVICE_STATUS" | grep -q "active (running)"; then
            echo "✅ Service started successfully"
            exit 0
        else
            echo "❌ Service failed to start"
            echo "$SERVICE_STATUS"
            exit 1
        fi
    else
        echo "⚠️  Could not determine service status"
        echo "Service status output:"
        echo "$SERVICE_STATUS"
        exit 1
    fi
    
elif echo "$PACKAGE_CHECK" | grep -q "No QEMU guest agent configured"; then
    echo "❌ Guest agent not configured in Proxmox"
    echo "This should have been fixed in Step 2. Please check manually:"
    echo "  qm config $VMID | grep '^agent:'"
    exit 1
    
elif echo "$PACKAGE_CHECK" | grep -q "QEMU guest agent is not running"; then
    echo "⚠️  Guest agent configured but service not running"
    echo "The package may not be installed, or the service isn't started"
    echo ""
    echo "=========================================="
    echo "PACKAGE INSTALLATION REQUIRED"
    echo "=========================================="
    echo ""
    echo "The qemu-guest-agent package needs to be installed inside the VM."
    echo ""
    echo "Options:"
    echo "1. SSH into the VM (if you have the IP and access)"
    echo "2. Use Proxmox console (qm terminal $VMID or via web UI)"
    echo ""
    echo "Then run inside the VM:"
    echo "  sudo apt-get update"
    echo "  sudo apt-get install -y qemu-guest-agent"
    echo "  sudo systemctl enable --now qemu-guest-agent"
    echo ""
    
    # Try to get VM IP
    echo "Attempting to get VM IP address..."
    VM_IP=$(qm guest exec $VMID -- hostname -I 2>&1 | awk '{print $1}' || echo "")
    if [ -n "$VM_IP" ] && [ "$VM_IP" != "QEMU" ] && [ "$VM_IP" != "No" ]; then
        echo "VM IP: $VM_IP"
        echo ""
        echo "You can try SSH:"
        echo "  ssh admin@$VM_IP"
    else
        echo "Could not get VM IP via guest exec"
        echo "Use Proxmox console or check network configuration"
    fi
    exit 1
    
else
    echo "❌ qemu-guest-agent package is NOT installed"
    echo ""
    echo "Error details:"
    echo "$PACKAGE_CHECK"
    echo ""
    echo "=========================================="
    echo "PACKAGE INSTALLATION REQUIRED"
    echo "=========================================="
    echo ""
    echo "The qemu-guest-agent package needs to be installed inside the VM."
    echo ""
    echo "Options:"
    echo "1. SSH into the VM (if you have the IP and access)"
    echo "2. Use Proxmox console (qm terminal $VMID or via web UI)"
    echo ""
    echo "Then run inside the VM:"
    echo "  sudo apt-get update"
    echo "  sudo apt-get install -y qemu-guest-agent"
    echo "  sudo systemctl enable --now qemu-guest-agent"
    echo ""
    exit 1
fi

