#!/bin/bash
set -euo pipefail

# Verify Proxmox Resources Script
# This script connects to Proxmox and verifies actual resource names

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
OUTPUT_DIR="${PROJECT_ROOT}/docs/proxmox-review"

# 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} $*"
}

# Load environment
load_env() {
    if [ -f "${PROJECT_ROOT}/.env" ]; then
        source "${PROJECT_ROOT}/.env"
    fi
    
    PROXMOX_1_API_URL="${PROXMOX_1_API_URL:-https://192.168.11.10:8006}"
    PROXMOX_1_USER="${PROXMOX_1_USER:-root}"
    PROXMOX_1_PASS="${PROXMOX_1_PASS:-}"
    PROXMOX_1_API_TOKEN="${PROXMOX_1_API_TOKEN:-}"
    PROXMOX_1_INSECURE="${PROXMOX_1_INSECURE_SKIP_TLS_VERIFY:-false}"
    
    PROXMOX_2_API_URL="${PROXMOX_2_API_URL:-https://192.168.11.11:8006}"
    PROXMOX_2_USER="${PROXMOX_2_USER:-root}"
    PROXMOX_2_PASS="${PROXMOX_2_PASS:-}"
    PROXMOX_2_API_TOKEN="${PROXMOX_2_API_TOKEN:-}"
    PROXMOX_2_INSECURE="${PROXMOX_2_INSECURE_SKIP_TLS_VERIFY:-false}"
}

# Authenticate and get ticket
get_ticket() {
    local api_url=$1
    local username=$2
    local password=$3
    local insecure=$4
    
    local curl_opts=()
    if [ "${insecure}" = "true" ]; then
        curl_opts+=("-k")
    fi
    
    local response
    response=$(curl -s "${curl_opts[@]}" -X POST \
        -d "username=${username}&password=${password}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null || echo "")
    
    if [ -z "${response}" ]; then
        echo ""
        return 1
    fi
    
    if command -v jq &> /dev/null; then
        echo "${response}" | jq -r '.data.ticket // empty'
    else
        echo "${response}" | grep -o '"ticket":"[^"]*' | cut -d'"' -f4
    fi
}

# Get CSRF token
get_csrf() {
    local api_url=$1
    local username=$2
    local password=$3
    local insecure=$4
    
    local curl_opts=()
    if [ "${insecure}" = "true" ]; then
        curl_opts+=("-k")
    fi
    
    local response
    response=$(curl -s "${curl_opts[@]}" -X POST \
        -d "username=${username}&password=${password}" \
        "${api_url}/api2/json/access/ticket" 2>/dev/null || echo "")
    
    if [ -z "${response}" ]; then
        echo ""
        return 1
    fi
    
    if command -v jq &> /dev/null; then
        echo "${response}" | jq -r '.data.CSRFPreventionToken // empty'
    else
        echo "${response}" | grep -o '"CSRFPreventionToken":"[^"]*' | cut -d'"' -f4
    fi
}

# API call
api_call() {
    local api_url=$1
    local endpoint=$2
    local ticket=$3
    local csrf=$4
    local insecure=$5
    
    local curl_opts=(-s -f)
    if [ "${insecure}" = "true" ]; then
        curl_opts+=("-k")
    fi
    
    local headers=()
    if [ -n "${csrf}" ]; then
        headers+=(-H "CSRFPreventionToken: ${csrf}")
    fi
    
    curl "${curl_opts[@]}" "${headers[@]}" \
        -b "PVEAuthCookie=${ticket}" \
        "${api_url}/api2/json${endpoint}" 2>/dev/null || echo ""
}

# Verify resources for an instance
verify_instance() {
    local instance_num=$1
    local api_url=$2
    local username=$3
    local password=$4
    local insecure=$5
    
    log "Verifying Instance ${instance_num} (${api_url})..."
    
    if [ -z "${password}" ]; then
        log_warning "Password not set, skipping verification"
        return 1
    fi
    
    local ticket
    ticket=$(get_ticket "${api_url}" "${username}" "${password}" "${insecure}")
    
    if [ -z "${ticket}" ]; then
        log_error "Failed to authenticate to Instance ${instance_num}"
        return 1
    fi
    
    local csrf
    csrf=$(get_csrf "${api_url}" "${username}" "${password}" "${insecure}")
    
    log_success "Authenticated to Instance ${instance_num}"
    
    # Get nodes
    log "  Fetching nodes..."
    local nodes
    nodes=$(api_call "${api_url}" "/nodes" "${ticket}" "${csrf}" "${insecure}")
    
    # Get storage
    log "  Fetching storage pools..."
    local storage
    storage=$(api_call "${api_url}" "/storage" "${ticket}" "${csrf}" "${insecure}")
    
    # Get version
    log "  Fetching version..."
    local version
    version=$(api_call "${api_url}" "/version" "${ticket}" "${csrf}" "${insecure}")
    
    # Save results
    local output_file="${OUTPUT_DIR}/proxmox-${instance_num}-resources-$(date +%Y%m%d_%H%M%S).json"
    {
        echo "{"
        echo "  \"instance\": ${instance_num},"
        echo "  \"api_url\": \"${api_url}\","
        echo "  \"timestamp\": \"$(date -Iseconds)\","
        echo "  \"nodes\": ${nodes:-null},"
        echo "  \"storage\": ${storage:-null},"
        echo "  \"version\": ${version:-null}"
        echo "}"
    } > "${output_file}"
    
    log_success "Resources saved to ${output_file}"
    
    # Display summary
    if command -v jq &> /dev/null && [ -n "${nodes}" ]; then
        log "  Nodes:"
        echo "${nodes}" | jq -r '.data[]? | "    - \(.node) (status: \(.status // "unknown"))"' || true
        
        log "  Storage Pools:"
        echo "${storage}" | jq -r '.data[]? | "    - \(.storage) (type: \(.type), enabled: \(.enabled))"' || true
    fi
    
    return 0
}

main() {
    log "Starting Proxmox Resource Verification..."
    log "=========================================="
    
    load_env
    mkdir -p "${OUTPUT_DIR}"
    
    # Verify Instance 1
    verify_instance 1 \
        "${PROXMOX_1_API_URL}" \
        "${PROXMOX_1_USER}" \
        "${PROXMOX_1_PASS}" \
        "${PROXMOX_1_INSECURE}" || log_warning "Instance 1 verification failed"
    
    log ""
    
    # Verify Instance 2
    verify_instance 2 \
        "${PROXMOX_2_API_URL}" \
        "${PROXMOX_2_USER}" \
        "${PROXMOX_2_PASS}" \
        "${PROXMOX_2_INSECURE}" || log_warning "Instance 2 verification failed"
    
    log ""
    log "=========================================="
    log_success "Verification completed!"
    log ""
    log "Review resource files in: ${OUTPUT_DIR}"
}

main "$@"

