#!/bin/bash
# start-vms-simple.sh
# Start VMs using Proxmox API with simple curl commands

set -euo pipefail

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

# Load environment
if [ -f "${PROJECT_ROOT}/.env" ]; then
    set -a
    source "${PROJECT_ROOT}/.env"
    set +a
fi

PROXMOX_PASS="${PROXMOX_ROOT_PASS:-L@kers2010}"
PROXMOX_1_URL="https://192.168.11.10:8006"
PROXMOX_2_URL="https://192.168.11.11:8006"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
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_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

# Start VM using API
start_vm_api() {
    local api_url=$1
    local node=$2
    local vmid=$3
    local password=$4
    
    # Get ticket
    local ticket_response
    ticket_response=$(curl -k -s -X POST \
        -d "username=root@pam&password=${password}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null)
    
    if echo "${ticket_response}" | grep -q "authentication failure"; then
        return 1
    fi
    
    local ticket csrf
    if command -v jq &> /dev/null; then
        ticket=$(echo "${ticket_response}" | jq -r '.data.ticket // empty' 2>/dev/null)
        csrf=$(echo "${ticket_response}" | jq -r '.data.CSRFPreventionToken // empty' 2>/dev/null)
    else
        ticket=$(echo "${ticket_response}" | grep -o '"ticket":"[^"]*' | head -1 | cut -d'"' -f4)
        csrf=$(echo "${ticket_response}" | grep -o '"CSRFPreventionToken":"[^"]*' | head -1 | cut -d'"' -f4)
    fi
    
    if [ -z "${ticket}" ] || [ -z "${csrf}" ]; then
        return 1
    fi
    
    # Start VM
    local start_response
    start_response=$(curl -k -s -X POST \
        -H "CSRFPreventionToken: ${csrf}" \
        -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json/nodes/${node}/qemu/${vmid}/status/start" 2>/dev/null)
    
    if echo "${start_response}" | grep -q '"data":null'; then
        return 0
    fi
    
    return 1
}

main() {
    log "Starting SMOM-DBIS-138 VMs..."
    log ""
    
    # Site 1 VMs
    log "Site 1 (ml110-01):"
    local site1_vms=("118:nginx-proxy-vm" "132:smom-validator-01" "133:smom-validator-02" "127:smom-sentry-01" "128:smom-sentry-02" "123:smom-rpc-node-01" "124:smom-rpc-node-02" "121:smom-management")
    
    for vm_entry in "${site1_vms[@]}"; do
        IFS=':' read -r vmid vmname <<< "${vm_entry}"
        log "  Starting ${vmname} (${vmid})..."
        if start_vm_api "${PROXMOX_1_URL}" "ml110-01" "${vmid}" "${PROXMOX_PASS}"; then
            log_success "    ${vmname} started"
        else
            log_error "    Failed to start ${vmname}"
        fi
        sleep 1
    done
    
    log ""
    
    # Site 2 VMs
    log "Site 2 (r630-01):"
    local site2_vms=("119:cloudflare-tunnel-vm" "134:smom-validator-03" "122:smom-validator-04" "129:smom-sentry-03" "130:smom-sentry-04" "125:smom-rpc-node-03" "126:smom-rpc-node-04" "131:smom-services" "120:smom-blockscout" "122:smom-monitoring")
    
    for vm_entry in "${site2_vms[@]}"; do
        IFS=':' read -r vmid vmname <<< "${vm_entry}"
        log "  Starting ${vmname} (${vmid})..."
        if start_vm_api "${PROXMOX_2_URL}" "r630-01" "${vmid}" "${PROXMOX_PASS}"; then
            log_success "    ${vmname} started"
        else
            log_error "    Failed to start ${vmname}"
        fi
        sleep 1
    done
    
    log ""
    log_success "VM startup initiated!"
    log ""
    log "Waiting 30 seconds for VMs to initialize..."
    sleep 30
    
    log "Checking VM status..."
    kubectl get proxmoxvm -A -o custom-columns=NAME:.metadata.name,VMID:.status.vmId,STATE:.status.state --sort-by=.metadata.name | head -20
    log ""
}

main "$@"

