#!/bin/bash
# discover-proxmox-resources.sh
# Discovers Proxmox resources (storage, networks, templates, nodes) and outputs JSON

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
INSTANCE1_ENDPOINT="${PROXMOX_INSTANCE1:-https://192.168.11.10:8006}"
INSTANCE2_ENDPOINT="${PROXMOX_INSTANCE2:-https://192.168.11.11:8006}"
OUTPUT_DIR="${OUTPUT_DIR:-./docs/proxmox-review}"

# Check if pvesh is available
if ! command -v pvesh &> /dev/null; then
    echo -e "${YELLOW}Warning: pvesh not found. Install Proxmox VE tools or use API directly.${NC}"
    echo "This script requires pvesh CLI tool or can be adapted to use curl/API."
    exit 1
fi

# Function to discover resources for an instance
discover_instance() {
    local endpoint=$1
    local instance_name=$2
    local output_file="${OUTPUT_DIR}/resources-${instance_name}.json"
    
    echo -e "${GREEN}Discovering resources for ${instance_name}...${NC}"
    
    # Create output directory
    mkdir -p "${OUTPUT_DIR}"
    
    # Discover nodes
    echo "  - Discovering nodes..."
    local nodes
    nodes=$(pvesh get /nodes --output-format json 2>/dev/null || echo "[]")
    
    # Discover storage
    echo "  - Discovering storage pools..."
    local storage
    storage=$(pvesh get /storage --output-format json 2>/dev/null || echo "[]")
    
    # Discover networks (for each node)
    echo "  - Discovering network bridges..."
    local networks="[]"
    if [ -n "$nodes" ] && [ "$nodes" != "[]" ]; then
        # Extract node names from nodes JSON (simplified - would need jq for proper parsing)
        # For now, we'll try common node names
        for node in ML110-01 R630-01; do
            local node_networks
            node_networks=$(pvesh get "/nodes/${node}/network" --output-format json 2>/dev/null || echo "[]")
            if [ "$node_networks" != "[]" ]; then
                networks="$node_networks"
                break
            fi
        done
    fi
    
    # Discover templates (for each storage pool)
    echo "  - Discovering OS templates..."
    local templates="[]"
    if [ -n "$storage" ] && [ "$storage" != "[]" ]; then
        # Try to get templates from common storage pools
        for storage_pool in local local-lvm; do
            for node in ML110-01 R630-01; do
                local storage_templates
                storage_templates=$(pvesh get "/nodes/${node}/storage/${storage_pool}/content" --output-format json 2>/dev/null || echo "[]")
                if [ "$storage_templates" != "[]" ]; then
                    templates="$storage_templates"
                    break 2
                fi
            done
        done
    fi
    
    # Combine all resources
    cat > "${output_file}" <<EOF
{
  "instance": "${instance_name}",
  "endpoint": "${endpoint}",
  "discovered_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "nodes": ${nodes},
  "storage": ${storage},
  "networks": ${networks},
  "templates": ${templates}
}
EOF
    
    echo -e "${GREEN}✓ Resources saved to ${output_file}${NC}"
}

# Function to discover via API (if pvesh not available)
discover_via_api() {
    local endpoint=$1
    local instance_name=$2
    local username="${PROXMOX_USERNAME:-}"
    local password="${PROXMOX_PASSWORD:-}"
    local token="${PROXMOX_TOKEN:-}"
    
    if [ -z "$token" ] && [ -z "$username" ]; then
        echo -e "${RED}Error: PROXMOX_TOKEN or PROXMOX_USERNAME/PROXMOX_PASSWORD required${NC}"
        return 1
    fi
    
    echo -e "${GREEN}Discovering resources for ${instance_name} via API...${NC}"
    
    # Authenticate and get ticket (if using username/password)
    local auth_header=""
    if [ -n "$token" ]; then
        auth_header="Authorization: PVEAPIToken ${token}"
    else
        # Get ticket (simplified - would need proper auth flow)
        echo -e "${YELLOW}Note: Username/password auth requires ticket-based authentication${NC}"
        return 1
    fi
    
    # Discover resources via API
    local output_file="${OUTPUT_DIR}/resources-${instance_name}.json"
    mkdir -p "${OUTPUT_DIR}"
    
    # Get nodes
    local nodes
    nodes=$(curl -s -k -H "${auth_header}" "${endpoint}/api2/json/nodes" | jq -r '.data // []' || echo "[]")
    
    # Get storage
    local storage
    storage=$(curl -s -k -H "${auth_header}" "${endpoint}/api2/json/storage" | jq -r '.data // []' || echo "[]")
    
    # Combine resources
    cat > "${output_file}" <<EOF
{
  "instance": "${instance_name}",
  "endpoint": "${endpoint}",
  "discovered_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "nodes": ${nodes},
  "storage": ${storage}
}
EOF
    
    echo -e "${GREEN}✓ Resources saved to ${output_file}${NC}"
}

# Main execution
main() {
    echo -e "${GREEN}=== Proxmox Resource Discovery ===${NC}"
    echo ""
    
    # Try pvesh first, fall back to API
    if command -v pvesh &> /dev/null; then
        echo "Using pvesh CLI..."
        discover_instance "${INSTANCE1_ENDPOINT}" "instance-1" || true
        discover_instance "${INSTANCE2_ENDPOINT}" "instance-2" || true
    elif command -v curl &> /dev/null && command -v jq &> /dev/null; then
        echo "Using API with curl..."
        discover_via_api "${INSTANCE1_ENDPOINT}" "instance-1" || true
        discover_via_api "${INSTANCE2_ENDPOINT}" "instance-2" || true
    else
        echo -e "${RED}Error: pvesh, curl, or jq required${NC}"
        exit 1
    fi
    
    echo ""
    echo -e "${GREEN}=== Discovery Complete ===${NC}"
    echo "Output files:"
    ls -lh "${OUTPUT_DIR}"/resources-*.json 2>/dev/null || echo "  (No files generated)"
    echo ""
    echo "Next steps:"
    echo "  1. Review generated JSON files"
    echo "  2. Update docs/proxmox/RESOURCE_INVENTORY.md with actual values"
    echo "  3. Update example manifests with verified resource names"
}

# Run main
main "$@"

