#!/bin/bash
# Check for orphaned storage volumes and verify if VMs exist elsewhere
# Helps identify if storage volumes on r630-02 correspond to VMs on other nodes

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/load-physical-inventory.sh" 2>/dev/null || true

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_section() { echo -e "\n${CYAN}=== $1 ===${NC}\n"; }

R630_02_IP="${PROXMOX_HOST_R630_02:-192.168.11.12}"
R630_02_PASS="${PROXMOX_PASS_R630_02:-password}"

# Orphaned VMIDs from storage
ORPHANED_VMIDS=(100 101 102 103 104 105 130 5000 6200 7800 7801 7802 7810 7811)

log_section "Orphaned Storage VM Check"

log_info "Checking for VMs with these VMIDs on all nodes..."
log_info "Orphaned VMIDs: ${ORPHANED_VMIDS[*]}"
echo ""

# Check all nodes
for node in "ml110:192.168.11.10:L@kers2010" "r630-01:192.168.11.11:password" "r630-02:192.168.11.12:password"; do
    IFS=: read -r name ip pass <<< "$node"
    
    log_section "Checking $name ($ip)"
    
    # Check containers
    containers=$(sshpass -p "$pass" ssh -o StrictHostKeyChecking=no root@"$ip" \
        "pct list 2>/dev/null | awk 'NR>1 {print \$1}'" 2>/dev/null || echo "")
    
    # Check VMs
    vms=$(sshpass -p "$pass" ssh -o StrictHostKeyChecking=no root@"$ip" \
        "qm list 2>/dev/null | awk 'NR>1 {print \$1}'" 2>/dev/null || echo "")
    
    echo "Found containers: $(echo $containers | wc -w)"
    echo "Found VMs: $(echo $vms | wc -w)"
    
    # Check for orphaned VMIDs
    found_vmids=()
    for vmid in "${ORPHANED_VMIDS[@]}"; do
        if echo "$containers $vms" | grep -q "\b$vmid\b"; then
            found_vmids+=($vmid)
        fi
    done
    
    if [ ${#found_vmids[@]} -gt 0 ]; then
        log_warn "Found VMIDs on $name: ${found_vmids[*]}"
        for vmid in "${found_vmids[@]}"; do
            sshpass -p "$pass" ssh -o StrictHostKeyChecking=no root@"$ip" \
                "pct list | grep \"^$vmid\" || qm list | grep \"^$vmid\"" 2>/dev/null || true
        done
    else
        log_info "No orphaned VMIDs found on $name"
    fi
    echo ""
done

log_section "Storage Volume Check on r630-02"

sshpass -p "$R630_02_PASS" ssh -o StrictHostKeyChecking=no root@"$R630_02_IP" bash <<'ENDSSH' 2>/dev/null
    echo "=== thin1 Storage Volumes ==="
    pvesm list thin1 2>/dev/null | grep -E "vm-100|vm-101|vm-102|vm-103|vm-104|vm-105|vm-130|vm-5000|vm-6200" || echo "No volumes found"
    echo ""
    echo "=== thin4 Storage Volumes ==="
    pvesm list thin4 2>/dev/null | grep -E "vm-7800|vm-7801|vm-7802|vm-7810|vm-7811" || echo "No volumes found"
    echo ""
    echo "=== VM Registration Status ==="
    echo "Containers: $(pct list 2>/dev/null | tail -n +2 | wc -l)"
    echo "VMs: $(qm list 2>/dev/null | tail -n +2 | wc -l)"
ENDSSH

log_section "Summary"

log_info "Orphaned storage volumes exist on r630-02 but VMs are not registered."
log_info "See docs/R630_02_VM_RECOVERY_ANALYSIS.md for analysis and recommendations."
