#!/bin/bash
set -euo pipefail

# Infrastructure Discovery Script
# Discovers all infrastructure components for a site

SITE="${SITE:-}"
OUTPUT_DIR="${OUTPUT_DIR:-/tmp/infrastructure-inventory}"

log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2
}

error() {
    log "ERROR: $*"
    exit 1
}

check_prerequisites() {
    if [ -z "${SITE}" ]; then
        error "SITE environment variable is required"
    fi
    
    mkdir -p "${OUTPUT_DIR}"
}

discover_proxmox() {
    log "Discovering Proxmox infrastructure..."
    
    # Check if discovery script exists
    if [ -f "../../proxmox/scripts/discover-cluster.sh" ]; then
        ../../proxmox/scripts/discover-cluster.sh --site "${SITE}" > "${OUTPUT_DIR}/proxmox-${SITE}.json" 2>&1 || log "  ⚠️  Proxmox discovery failed"
    else
        log "  ⚠️  Proxmox discovery script not found"
    fi
}

discover_omada() {
    log "Discovering Omada infrastructure..."
    
    if [ -f "../../omada/scripts/discover-aps.sh" ]; then
        ../../omada/scripts/discover-aps.sh --site "${SITE}" > "${OUTPUT_DIR}/omada-${SITE}.json" 2>&1 || log "  ⚠️  Omada discovery failed"
    else
        log "  ⚠️  Omada discovery script not found"
    fi
}

discover_network() {
    log "Discovering network infrastructure..."
    
    # Network discovery would use SNMP or other protocols
    log "  ⚠️  Network discovery not yet implemented"
}

generate_inventory() {
    log "Generating inventory report..."
    
    REPORT_FILE="${OUTPUT_DIR}/inventory-${SITE}-$(date +%Y%m%d-%H%M%S).json"
    
    cat > "${REPORT_FILE}" <<EOF
{
  "site": "${SITE}",
  "discovery_date": "$(date -Iseconds)",
  "components": {
    "proxmox": {
      "file": "proxmox-${SITE}.json",
      "status": "$([ -f "${OUTPUT_DIR}/proxmox-${SITE}.json" ] && echo "discovered" || echo "failed")"
    },
    "omada": {
      "file": "omada-${SITE}.json",
      "status": "$([ -f "${OUTPUT_DIR}/omada-${SITE}.json" ] && echo "discovered" || echo "failed")"
    },
    "network": {
      "status": "not_implemented"
    }
  }
}
EOF
    
    log "Inventory report generated: ${REPORT_FILE}"
    cat "${REPORT_FILE}"
}

main() {
    log "Starting infrastructure discovery for site: ${SITE}"
    
    check_prerequisites
    discover_proxmox
    discover_omada
    discover_network
    generate_inventory
    
    log "Discovery completed! Results in: ${OUTPUT_DIR}"
}

main "$@"

