#!/bin/bash
# start-vms-via-api.sh
# Start VMs via Proxmox API

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
    source "${PROJECT_ROOT}/.env"
fi

PROXMOX_ROOT_PASS="${PROXMOX_ROOT_PASS:-L@kers2010}"
PROXMOX_1_API_URL="${PROXMOX_1_API_URL:-https://192.168.11.10:8006}"
PROXMOX_2_API_URL="${PROXMOX_2_API_URL:-https://192.168.11.11:8006}"

# 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_error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ❌${NC} $*"
}

# Get authentication ticket
get_ticket() {
    local api_url=$1
    local username=$2
    local password=$3
    
    local response
    response=$(curl -k -s -X POST \
        -d "username=${username}&password=${password}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null || echo "")
    
    if [ -z "${response}" ] || echo "${response}" | grep -q "authentication failure"; then
        echo ""
        return 1
    fi
    
    if command -v jq &> /dev/null; then
        local ticket
        ticket=$(echo "${response}" | jq -r '.data.ticket // empty' 2>/dev/null)
        if [ -n "${ticket}" ] && [ "${ticket}" != "null" ]; then
            echo "${ticket}"
            return 0
        fi
    fi
    
    # Fallback: extract from JSON manually
    echo "${response}" | grep -o '"ticket":"[^"]*' | head -1 | cut -d'"' -f4
}

# Get CSRF token
get_csrf() {
    local api_url=$1
    local username=$2
    local password=$3
    
    local response
    response=$(curl -k -s -X POST \
        -d "username=${username}&password=${password}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null || echo "")
    
    if [ -z "${response}" ] || echo "${response}" | grep -q "authentication failure"; then
        echo ""
        return 1
    fi
    
    if command -v jq &> /dev/null; then
        local csrf
        csrf=$(echo "${response}" | jq -r '.data.CSRFPreventionToken // empty' 2>/dev/null)
        if [ -n "${csrf}" ] && [ "${csrf}" != "null" ]; then
            echo "${csrf}"
            return 0
        fi
    fi
    
    # Fallback: extract from JSON manually
    echo "${response}" | grep -o '"CSRFPreventionToken":"[^"]*' | head -1 | cut -d'"' -f4
}

# Start VM
start_vm() {
    local api_url=$1
    local ticket=$2
    local csrf=$3
    local node=$4
    local vmid=$5
    
    local response
    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 || echo "")
    
    if echo "${response}" | grep -q '"data":null'; then
        return 0
    fi
    
    return 1
}

main() {
    log "=========================================="
    log "Starting SMOM-DBIS-138 VMs via Proxmox API"
    log "=========================================="
    log ""
    
    # Site 1 (ml110-01)
    log "Authenticating to Site 1 (ml110-01)..."
    local ticket1 csrf1
    ticket1=$(get_ticket "${PROXMOX_1_API_URL}" "root@pam" "${PROXMOX_ROOT_PASS}")
    csrf1=$(get_csrf "${PROXMOX_1_API_URL}" "root@pam" "${PROXMOX_ROOT_PASS}")
    
    if [ -z "${ticket1}" ]; then
        log_error "Failed to authenticate to Site 1"
        return 1
    fi
    
    log_success "Authenticated to Site 1"
    
    # Site 1 VMs
    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")
    
    log "Starting Site 1 VMs..."
    for vm_entry in "${site1_vms[@]}"; do
        IFS=':' read -r vmid vmname <<< "${vm_entry}"
        log "  Starting ${vmname} (VMID: ${vmid})..."
        if start_vm "${PROXMOX_1_API_URL}" "${ticket1}" "${csrf1}" "ml110-01" "${vmid}"; then
            log_success "  ${vmname} started"
        else
            log_error "  Failed to start ${vmname}"
        fi
    done
    
    log ""
    
    # Site 2 (r630-01)
    log "Authenticating to Site 2 (r630-01)..."
    local ticket2 csrf2
    ticket2=$(get_ticket "${PROXMOX_2_API_URL}" "root@pam" "${PROXMOX_ROOT_PASS}")
    csrf2=$(get_csrf "${PROXMOX_2_API_URL}" "root@pam" "${PROXMOX_ROOT_PASS}")
    
    if [ -z "${ticket2}" ]; then
        log_error "Failed to authenticate to Site 2"
        return 1
    fi
    
    log_success "Authenticated to Site 2"
    
    # Site 2 VMs
    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")
    
    log "Starting Site 2 VMs..."
    for vm_entry in "${site2_vms[@]}"; do
        IFS=':' read -r vmid vmname <<< "${vm_entry}"
        log "  Starting ${vmname} (VMID: ${vmid})..."
        if start_vm "${PROXMOX_2_API_URL}" "${ticket2}" "${csrf2}" "r630-01" "${vmid}"; then
            log_success "  ${vmname} started"
        else
            log_error "  Failed to start ${vmname}"
        fi
    done
    
    log ""
    log "=========================================="
    log_success "VM startup initiated!"
    log ""
    log "Waiting for VMs to boot (this may take 2-5 minutes)..."
    log "Monitor with: kubectl get proxmoxvm -A -w"
    log ""
}

main "$@"

