#!/bin/bash
# Update VM template files with current Kubernetes configurations
# Preserves metadata, labels, and userData sections

set -euo pipefail

echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  UPDATE VM TEMPLATE FILES"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""

# Function to update a VM template file
update_template_file() {
    local file_path=$1
    local vm_name=$2
    local namespace=$3
    local node=$4
    local cpu=$5
    local memory=$6
    local disk=$7
    local storage=$8
    local image=$9
    local network=${10}
    local site=${11}
    
    # Read existing file to preserve metadata and userData
    if [ -f "$file_path" ]; then
        # Extract metadata section (including labels)
        metadata_section=$(awk '/^metadata:/,/^spec:/ {print}' "$file_path" | head -n -1)
        # Extract userData section if it exists
        userdata_section=$(awk '/userData:/,/providerConfigRef:/ {print}' "$file_path" | head -n -1 || echo "")
        # Extract providerConfigRef if it exists
        provider_config=$(grep -A 2 "providerConfigRef:" "$file_path" || echo "")
    else
        metadata_section="metadata:
  name: $vm_name
  namespace: $namespace"
        userdata_section=""
        provider_config="  providerConfigRef:
    name: proxmox-provider-config"
    fi
    
    # Create updated file
    {
        echo "apiVersion: proxmox.sankofa.nexus/v1alpha1"
        echo "kind: ProxmoxVM"
        echo "$metadata_section"
        echo "spec:"
        echo "  forProvider:"
        echo "    node: \"$node\""
        echo "    name: \"$vm_name\""
        echo "    cpu: $cpu"
        echo "    memory: \"$memory\""
        echo "    disk: \"$disk\""
        echo "    storage: \"$storage\""
        echo "    network: \"$network\""
        echo "    image: \"$image\""
        echo "    site: \"$site\""
        if [ -n "$userdata_section" ]; then
            echo "$userdata_section"
        fi
        if [ -n "$provider_config" ]; then
            echo "$provider_config"
        fi
    } > "$file_path.tmp" && mv "$file_path.tmp" "$file_path"
    
    echo "  ✅ Updated: $file_path"
}

# Get VM configurations from Kubernetes
echo "Step 1: Fetching VM configurations from Kubernetes..."
VM_CONFIGS=$(kubectl get proxmoxvms -A -o json 2>/dev/null | jq -r '.items[] | 
    select(.spec.forProvider.node == "r630-01" or .spec.forProvider.node == "ml110-01") | 
    "\(.metadata.namespace)|\(.metadata.name)|\(.spec.forProvider.node)|\(.spec.forProvider.cpu)|\(.spec.forProvider.memory)|\(.spec.forProvider.disk)|\(.spec.forProvider.storage)|\(.spec.forProvider.image)|\(.spec.forProvider.network)|\(.spec.forProvider.site)"' | sort)

UPDATED_COUNT=0

# Update SMOM-DBIS-138 templates
echo ""
echo "Step 2: Updating SMOM-DBIS-138 VM templates..."
while IFS='|' read -r namespace name node cpu memory disk storage image network site; do
    case "$name" in
        smom-validator-01)
            update_template_file "examples/production/smom-dbis-138/validator-01.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-validator-02)
            update_template_file "examples/production/smom-dbis-138/validator-02.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-validator-03)
            update_template_file "examples/production/smom-dbis-138/validator-03.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-validator-04)
            update_template_file "examples/production/smom-dbis-138/validator-04.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-sentry-01)
            update_template_file "examples/production/smom-dbis-138/sentry-01.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-sentry-02)
            update_template_file "examples/production/smom-dbis-138/sentry-02.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-sentry-03)
            update_template_file "examples/production/smom-dbis-138/sentry-03.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-sentry-04)
            update_template_file "examples/production/smom-dbis-138/sentry-04.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        rpc-node-01)
            update_template_file "examples/production/smom-dbis-138/rpc-node-01.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        rpc-node-02)
            update_template_file "examples/production/smom-dbis-138/rpc-node-02.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        rpc-node-03)
            update_template_file "examples/production/smom-dbis-138/rpc-node-03.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        rpc-node-04)
            update_template_file "examples/production/smom-dbis-138/rpc-node-04.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-services)
            update_template_file "examples/production/smom-dbis-138/services.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        smom-blockscout)
            update_template_file "examples/production/smom-dbis-138/blockscout.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        monitoring)
            update_template_file "examples/production/smom-dbis-138/monitoring.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        management)
            update_template_file "examples/production/smom-dbis-138/management.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
    esac
done <<< "$VM_CONFIGS"

# Update Phoenix templates
echo ""
echo "Step 3: Updating Phoenix VM templates..."
while IFS='|' read -r namespace name node cpu memory disk storage image network site; do
    case "$name" in
        phoenix-as4-gateway)
            update_template_file "examples/production/phoenix/as4-gateway.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-business-integration-gateway)
            update_template_file "examples/production/phoenix/business-integration-gateway.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-codespaces-ide)
            update_template_file "examples/production/phoenix/codespaces-ide.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-devops-runner)
            update_template_file "examples/production/phoenix/devops-runner.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-dns-primary)
            update_template_file "examples/production/phoenix/dns-primary.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-email-server)
            update_template_file "examples/production/phoenix/email-server.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-financial-messaging-gateway)
            update_template_file "examples/production/phoenix/financial-messaging-gateway.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        phoenix-git-server)
            update_template_file "examples/production/phoenix/git-server.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
    esac
done <<< "$VM_CONFIGS"

# Update other production VMs
echo ""
echo "Step 4: Updating other production VM templates..."
while IFS='|' read -r namespace name node cpu memory disk storage image network site; do
    # Skip SMOM and Phoenix (already handled)
    if [[ "$name" =~ ^(smom-|phoenix-|rpc-node|monitoring|management)$ ]]; then
        continue
    fi
    # Skip example VMs
    if [[ "$name" =~ ^(basic-vm-001|large-vm-001|medium-vm-001|vm-100)$ ]]; then
        continue
    fi
    
    case "$name" in
        nginx-proxy-vm)
            update_template_file "examples/production/nginx-proxy-vm.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
        cloudflare-tunnel-vm)
            update_template_file "examples/production/cloudflare-tunnel-vm.yaml" "$name" "$namespace" "$node" "$cpu" "$memory" "$disk" "$storage" "$image" "$network" "$site"
            ((UPDATED_COUNT++))
            ;;
    esac
done <<< "$VM_CONFIGS"

echo ""
echo "═══════════════════════════════════════════════════════════════════════════════"
echo "  SUMMARY"
echo "═══════════════════════════════════════════════════════════════════════════════"
echo ""
echo "✅ Updated $UPDATED_COUNT VM template files"
echo ""
echo "All templates now reflect current Kubernetes configurations:"
echo "  - Storage: local-lvm (or as configured)"
echo "  - Image: 9000 (template) or local:iso/ubuntu-22.04-cloud.img"
echo "  - Current CPU, RAM, and Disk specifications"
echo "  - Metadata, labels, and userData preserved"

