#!/bin/bash
# start-smom-vms.sh
# Start all SMOM-DBIS-138 VMs via Proxmox API

set -euo pipefail

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

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

log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $*"
}

log_success() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] ✅${NC} $*"
}

log_warning() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] ⚠️${NC} $*"
}

log_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

# Get VM details
get_vm_details() {
    local vm_name=$1
    local vm_id
    local node
    local state
    
    vm_id=$(kubectl get proxmoxvm "${vm_name}" -n default -o jsonpath='{.status.vmId}' 2>/dev/null || echo "")
    node=$(kubectl get proxmoxvm "${vm_name}" -n default -o jsonpath='{.spec.forProvider.node}' 2>/dev/null || echo "")
    state=$(kubectl get proxmoxvm "${vm_name}" -n default -o jsonpath='{.status.state}' 2>/dev/null || echo "")
    
    if [ -z "${vm_id}" ] || [ "${vm_id}" = "0" ]; then
        echo ""
        return 1
    fi
    
    echo "${vm_id}|${node}|${state}"
}

# Start VM via Proxmox API (requires direct Proxmox access)
start_vm_direct() {
    local vm_id=$1
    local node=$2
    local proxmox_host=$3
    
    log "Starting VM ${vm_id} on ${node} via ${proxmox_host}..."
    
    # This would require Proxmox API credentials
    # For now, we'll provide instructions
    log_warning "Direct Proxmox API access required"
    log "To start VM manually:"
    log "  ssh root@${proxmox_host} 'qm start ${vm_id}'"
    log "  Or use Proxmox web UI: https://${proxmox_host}:8006"
    log ""
}

main() {
    log "=========================================="
    log "SMOM-DBIS-138 VM Startup Guide"
    log "=========================================="
    log ""
    log "VMs are created but in 'stopped' state."
    log "They need to be started to receive IP addresses."
    log ""
    
    # Check VM status
    local vms=(
        "nginx-proxy-vm"
        "cloudflare-tunnel-vm"
        "smom-validator-01"
        "smom-validator-02"
        "smom-validator-03"
        "smom-validator-04"
        "smom-sentry-01"
        "smom-sentry-02"
        "smom-sentry-03"
        "smom-sentry-04"
        "smom-rpc-node-01"
        "smom-rpc-node-02"
        "smom-rpc-node-03"
        "smom-rpc-node-04"
        "smom-services"
        "smom-blockscout"
        "smom-monitoring"
        "smom-management"
    )
    
    log "VM Status:"
    log "----------"
    
    local site1_vms=()
    local site2_vms=()
    
    for vm in "${vms[@]}"; do
        local details
        details=$(get_vm_details "${vm}" 2>/dev/null || echo "")
        
        if [ -n "${details}" ]; then
            IFS='|' read -r vm_id node state <<< "${details}"
            
            if [ "${node}" = "ml110-01" ]; then
                site1_vms+=("${vm_id}")
                log "  ${vm}: VMID=${vm_id}, Node=${node}, State=${state}"
            elif [ "${node}" = "r630-01" ]; then
                site2_vms+=("${vm_id}")
                log "  ${vm}: VMID=${vm_id}, Node=${node}, State=${state}"
            fi
        else
            log_warning "  ${vm}: Not found or no VMID"
        fi
    done
    
    log ""
    log "=========================================="
    log "Start VMs via Proxmox"
    log "=========================================="
    log ""
    log "Option 1: Via Proxmox Web UI"
    log "  1. Open: https://192.168.11.10:8006 (Site 1)"
    log "  2. Navigate to each VM"
    log "  3. Click 'Start'"
    log ""
    log "Option 2: Via SSH/Command Line"
    log ""
    log "Site 1 (ml110-01) - 192.168.11.10:"
    for vm_id in "${site1_vms[@]}"; do
        log "  ssh root@192.168.11.10 'qm start ${vm_id}'"
    done
    log ""
    log "Site 2 (r630-01) - 192.168.11.11:"
    for vm_id in "${site2_vms[@]}"; do
        log "  ssh root@192.168.11.11 'qm start ${vm_id}'"
    done
    log ""
    log "Option 3: Wait for Auto-Start"
    log "  The Crossplane controller may start VMs automatically."
    log "  Monitor with: kubectl get proxmoxvm -A -w"
    log ""
    log "=========================================="
    log "After Starting VMs"
    log "=========================================="
    log ""
    log "1. Wait for VMs to boot (2-5 minutes)"
    log "2. Check IP addresses:"
    log "   ./scripts/get-smom-vm-ips.sh"
    log ""
    log "3. Verify deployment:"
    log "   ./scripts/verify-deployment.sh"
    log ""
    log "4. Proceed with configuration:"
    log "   See: docs/smom-dbis-138-next-steps.md"
    log ""
}

main "$@"

