#!/bin/bash
# Enhance guest agent verification in all VM YAML templates
# Adds detailed verification commands matching the check script

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TEMPLATES_DIR="$PROJECT_ROOT/examples/production"

# Enhanced verification block
ENHANCED_VERIFICATION='        # Verify packages are installed
        - |
          echo "=========================================="
          echo "Verifying required packages are installed..."
          echo "=========================================="
          for pkg in qemu-guest-agent curl wget net-tools chrony unattended-upgrades; do
            if ! dpkg -l | grep -q "^ii.*$pkg"; then
              echo "ERROR: Package $pkg is not installed"
              exit 1
            fi
            echo "✅ Package $pkg is installed"
          done
          echo "All required packages verified"
        
        # Verify qemu-guest-agent package details
        - |
          echo "=========================================="
          echo "Checking qemu-guest-agent package details..."
          echo "=========================================="
          if dpkg -l | grep -q "^ii.*qemu-guest-agent"; then
            echo "✅ qemu-guest-agent package IS installed"
            dpkg -l | grep qemu-guest-agent
          else
            echo "❌ qemu-guest-agent package is NOT installed"
            echo "Attempting to install..."
            apt-get update
            apt-get install -y qemu-guest-agent
          fi
        
        # Enable and start QEMU Guest Agent
        - |
          echo "=========================================="
          echo "Enabling and starting QEMU Guest Agent..."
          echo "=========================================="
          systemctl enable qemu-guest-agent
          systemctl start qemu-guest-agent
          echo "QEMU Guest Agent enabled and started"
        
        # Verify guest agent service is running
        - |
          echo "=========================================="
          echo "Verifying QEMU Guest Agent service status..."
          echo "=========================================="
          for i in {1..30}; do
            if systemctl is-active --quiet qemu-guest-agent; then
              echo "✅ QEMU Guest Agent service IS running"
              systemctl status qemu-guest-agent --no-pager -l
              exit 0
            fi
            echo "Waiting for QEMU Guest Agent to start... ($i/30)"
            sleep 1
          done
          echo "⚠️  WARNING: QEMU Guest Agent may not have started properly"
          systemctl status qemu-guest-agent --no-pager -l || true
          echo "Attempting to restart..."
          systemctl restart qemu-guest-agent
          sleep 3
          if systemctl is-active --quiet qemu-guest-agent; then
            echo "✅ QEMU Guest Agent started after restart"
          else
            echo "❌ QEMU Guest Agent failed to start"
          fi'

# Old verification block pattern (to be replaced)
OLD_PATTERN_START='        # Verify packages are installed'
OLD_PATTERN_END='          systemctl status qemu-guest-agent --no-pager || true'

echo "=========================================="
echo "Enhancing Guest Agent Verification"
echo "=========================================="
echo ""
echo "Target directory: $TEMPLATES_DIR"
echo ""

# Find all YAML files (excluding backups)
FILES=$(find "$TEMPLATES_DIR" -name "*.yaml" -type f ! -name "*.backup*" | sort)

if [ -z "$FILES" ]; then
    echo "No YAML files found in $TEMPLATES_DIR"
    exit 1
fi

UPDATED_COUNT=0
SKIPPED_COUNT=0

for file in $FILES; do
    # Check if file contains the old verification pattern
    if ! grep -q "Verifying required packages are installed" "$file"; then
        echo "⏭️  Skipping $file (no guest agent verification found)"
        ((SKIPPED_COUNT++))
        continue
    fi
    
    # Check if already enhanced
    if grep -q "Checking qemu-guest-agent package details" "$file"; then
        echo "✅ Already enhanced: $file"
        continue
    fi
    
    echo "📝 Processing: $file"
    
    # Create backup
    cp "$file" "${file}.backup-$(date +%Y%m%d-%H%M%S)"
    
    # Use Python for more reliable YAML manipulation
    python3 <<PYTHON_SCRIPT
import re
import sys

file_path = "$file"

with open(file_path, 'r') as f:
    content = f.read()

# Find the old verification block
old_pattern = r'        # Verify packages are installed.*?          systemctl status qemu-guest-agent --no-pager \|\| true'

# Enhanced verification block (properly indented)
enhanced = '''        # Verify packages are installed
        - |
          echo "=========================================="
          echo "Verifying required packages are installed..."
          echo "=========================================="
          for pkg in qemu-guest-agent curl wget net-tools chrony unattended-upgrades; do
            if ! dpkg -l | grep -q "^ii.*\\$pkg"; then
              echo "ERROR: Package \\$pkg is not installed"
              exit 1
            fi
            echo "✅ Package \\$pkg is installed"
          done
          echo "All required packages verified"
        
        # Verify qemu-guest-agent package details
        - |
          echo "=========================================="
          echo "Checking qemu-guest-agent package details..."
          echo "=========================================="
          if dpkg -l | grep -q "^ii.*qemu-guest-agent"; then
            echo "✅ qemu-guest-agent package IS installed"
            dpkg -l | grep qemu-guest-agent
          else
            echo "❌ qemu-guest-agent package is NOT installed"
            echo "Attempting to install..."
            apt-get update
            apt-get install -y qemu-guest-agent
          fi
        
        # Enable and start QEMU Guest Agent
        - |
          echo "=========================================="
          echo "Enabling and starting QEMU Guest Agent..."
          echo "=========================================="
          systemctl enable qemu-guest-agent
          systemctl start qemu-guest-agent
          echo "QEMU Guest Agent enabled and started"
        
        # Verify guest agent service is running
        - |
          echo "=========================================="
          echo "Verifying QEMU Guest Agent service status..."
          echo "=========================================="
          for i in {1..30}; do
            if systemctl is-active --quiet qemu-guest-agent; then
              echo "✅ QEMU Guest Agent service IS running"
              systemctl status qemu-guest-agent --no-pager -l
              exit 0
            fi
            echo "Waiting for QEMU Guest Agent to start... (\\$i/30)"
            sleep 1
          done
          echo "⚠️  WARNING: QEMU Guest Agent may not have started properly"
          systemctl status qemu-guest-agent --no-pager -l || true
          echo "Attempting to restart..."
          systemctl restart qemu-guest-agent
          sleep 3
          if systemctl is-active --quiet qemu-guest-agent; then
            echo "✅ QEMU Guest Agent started after restart"
          else
            echo "❌ QEMU Guest Agent failed to start"
          fi'''

# Try to match and replace
if re.search(old_pattern, content, re.DOTALL):
    new_content = re.sub(old_pattern, enhanced, content, flags=re.DOTALL)
    with open(file_path, 'w') as f:
        f.write(new_content)
    print(f"✅ Updated: {file_path}")
    sys.exit(0)
else:
    print(f"⚠️  Pattern not found in {file_path}")
    sys.exit(1)
PYTHON_SCRIPT
    
    if [ $? -eq 0 ]; then
        ((UPDATED_COUNT++))
    else
        echo "⚠️  Failed to update: $file"
    fi
done

echo ""
echo "=========================================="
echo "Summary"
echo "=========================================="
echo "✅ Updated: $UPDATED_COUNT files"
echo "⏭️  Skipped: $SKIPPED_COUNT files"
echo ""
echo "Done!"

