#!/bin/bash
# Network Configuration Validation Script
# Tests that cloud-init networking is properly disabled

set -euo pipefail

GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_pass() {
    echo -e "${GREEN}✓${NC} $1"
}

log_fail() {
    echo -e "${RED}✗${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}⚠${NC} $1"
}

# Test cloud-init network configuration
test_cloudinit_network_disabled() {
    local vm_id=$1

    echo "=== Network Configuration Validation ==="
    echo

    # Check if cloud-init network config disable file exists
    echo "1. Checking cloud-init network config is disabled..."
    if qm guest exec "$vm_id" -- test -f /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg 2>/dev/null; then
        log_pass "cloud-init network config file exists"

        # Check content
        local content
        content=$(qm guest exec "$vm_id" -- cat /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg 2>/dev/null || echo "")

        if echo "$content" | grep -q "network.*disabled"; then
            log_pass "cloud-init networking is properly disabled"
        else
            log_fail "cloud-init network config file exists but networking not disabled"
            echo "Content: $content"
            return 1
        fi
    else
        log_fail "cloud-init network disable config missing"
        log_warn "This template may experience network race conditions!"
        return 1
    fi

    echo
    echo "2. Testing network connectivity..."
    if qm guest exec "$vm_id" -- ping -c 3 -W 5 8.8.8.8 >/dev/null 2>&1; then
        log_pass "Network connectivity working (ping successful)"
    else
        log_fail "No network connectivity"
        return 1
    fi

    echo
    echo "3. Testing DNS resolution..."
    if qm guest exec "$vm_id" -- ping -c 2 -W 5 google.com >/dev/null 2>&1; then
        log_pass "DNS resolution working"
    else
        log_warn "DNS resolution failed (but may not be configured yet)"
    fi

    echo
    echo "4. Testing QEMU guest agent network info..."
    if qm agent "$vm_id" network-get-interfaces >/dev/null 2>&1; then
        log_pass "QEMU agent can read network interfaces"
    else
        log_fail "QEMU agent cannot read network interfaces"
        return 1
    fi

    echo
    echo "5. Checking network interface configuration..."
    local ip_output
    ip_output=$(qm guest exec "$vm_id" -- ip addr show 2>/dev/null || echo "")

    if echo "$ip_output" | grep -q "inet "; then
        log_pass "Network interface has IP address"
        echo "$ip_output" | grep "inet " | head -3
    else
        log_fail "No IP address assigned to interfaces"
        return 1
    fi

    echo
    log_pass "All network tests passed!"
    echo
    echo "SUMMARY:"
    echo "  - Cloud-init networking: DISABLED ✓"
    echo "  - Network connectivity: WORKING ✓"
    echo "  - QEMU agent: FUNCTIONAL ✓"
    echo
    echo "This template is properly configured for Proxmox network management."

    return 0
}

# Usage
usage() {
    cat <<EOF
Usage: $0 VM_ID

Tests network configuration of a Proxmox VM/template.

Validates:
  - Cloud-init network management is disabled
  - Network connectivity works
  - QEMU guest agent can read network info
  - IP address is assigned

Arguments:
  VM_ID    Proxmox VM ID to test

Example:
  $0 9000

EOF
}

# Main
main() {
    if [[ $# -lt 1 ]]; then
        usage
        exit 1
    fi

    local vm_id=$1

    # Check if VM exists
    if ! qm status "$vm_id" &>/dev/null; then
        echo "Error: VM $vm_id does not exist"
        exit 1
    fi

    # Check if VM is running
    local status
    status=$(qm status "$vm_id" | awk '{print $2}')

    if [[ "$status" != "running" ]]; then
        echo "Error: VM $vm_id is not running (status: $status)"
        echo "Start the VM first: qm start $vm_id"
        exit 1
    fi

    # Wait for QEMU agent
    echo "Waiting for QEMU guest agent..."
    local attempts=0
    while ! qm agent "$vm_id" ping &>/dev/null; do
        sleep 2
        ((attempts++))
        if [[ $attempts -gt 30 ]]; then
            echo "Error: QEMU guest agent not responding after 60 seconds"
            exit 1
        fi
    done

    log_pass "QEMU guest agent is responding"
    echo

    # Run tests
    test_cloudinit_network_disabled "$vm_id"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
