#!/bin/bash
# Fix guest agent configuration for VM 100
# Run on Proxmox node: root@ml110-01

set -e

VMID=100

echo "=========================================="
echo "Fixing Guest Agent for VM 100"
echo "=========================================="
echo ""

# Step 1: Check current status
echo "Step 1: Current Configuration"
echo "--------------------------------------"
echo "Checking if agent is configured..."
AGENT_CONFIG=$(qm config $VMID | grep '^agent:' || echo "")
if [ -z "$AGENT_CONFIG" ]; then
    echo "❌ Guest agent NOT configured"
else
    echo "Current: $AGENT_CONFIG"
fi
echo ""

# Step 2: Set guest agent
echo "Step 2: Setting Guest Agent"
echo "--------------------------------------"
echo "Setting agent=1..."
qm set $VMID --agent 1
if [ $? -eq 0 ]; then
    echo "✅ Guest agent enabled"
else
    echo "❌ Failed to set guest agent"
    exit 1
fi
echo ""

# Step 3: Verify the setting
echo "Step 3: Verification"
echo "--------------------------------------"
AGENT_VERIFY=$(qm config $VMID | grep '^agent:' || echo "")
if [ -z "$AGENT_VERIFY" ]; then
    echo "❌ ERROR: Guest agent still not configured!"
    echo ""
    echo "Trying alternative method..."
    # Try setting via config file directly
    CONFIG_FILE="/etc/pve/qemu-server/${VMID}.conf"
    if [ -f "$CONFIG_FILE" ]; then
        if ! grep -q "^agent:" "$CONFIG_FILE"; then
            echo "agent: 1" >> "$CONFIG_FILE"
            echo "✅ Added agent: 1 to config file"
        else
            sed -i 's/^agent:.*/agent: 1/' "$CONFIG_FILE"
            echo "✅ Updated agent in config file"
        fi
    fi
else
    echo "✅ Verified: $AGENT_VERIFY"
fi
echo ""

# Step 4: Show full agent-related config
echo "Step 4: Full Agent Configuration"
echo "--------------------------------------"
qm config $VMID | grep -E 'agent|qemu' || echo "No agent/qemu config found"
echo ""

# Step 5: Check if VM needs to be restarted
echo "Step 5: VM Status"
echo "--------------------------------------"
VM_STATUS=$(qm status $VMID | awk '{print $2}')
echo "VM Status: $VM_STATUS"
if [ "$VM_STATUS" = "running" ]; then
    echo ""
    echo "⚠️  VM is running - guest agent setting will take effect after restart"
    echo "   To apply immediately, restart the VM:"
    echo "   qm shutdown $VMID && sleep 5 && qm start $VMID"
else
    echo "✅ VM is stopped - guest agent will be active on next start"
fi
echo ""

echo "=========================================="
echo "Guest Agent Fix Complete"
echo "=========================================="
echo ""
echo "Final verification:"
echo "  qm config $VMID | grep '^agent:'"
echo ""

