#!/bin/bash
# Enable and fix storage configuration on r630-01 and r630-02
# Fixes storage configuration issues and enables LVM thin storage

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"; }

# Hosts
R630_01_IP="${PROXMOX_HOST_R630_01:-192.168.11.11}"
R630_01_PASS="${PROXMOX_PASS_R630_01:-password}"
R630_02_IP="${PROXMOX_HOST_R630_02:-192.168.11.12}"
R630_02_PASS="${PROXMOX_PASS_R630_02:-password}"

log_section "Storage Configuration Fix for r630-01 and r630-02"

# Fix r630-01 storage
log_section "Fixing r630-01 (${R630_01_IP}) Storage"

sshpass -p "$R630_01_PASS" ssh -o StrictHostKeyChecking=no root@"$R630_01_IP" bash <<'ENDSSH'
    echo "=== Current Storage Configuration ==="
    cat /etc/pve/storage.cfg 2>/dev/null | grep -A 5 "nodes pve" || echo "No storage configured for 'pve' node"
    echo ""
    
    echo "=== Current Volume Groups ==="
    vgs
    echo ""
    
    echo "=== Current Logical Volumes ==="
    lvs pve 2>/dev/null | head -10
    echo ""
    
    echo "=== Checking for thin pools ==="
    lvs pve -o lv_name,vg_name,attr,pool_lv 2>/dev/null | grep -E "thin|data" || echo "No thin pools found"
    echo ""
    
    echo "=== Fixing Storage Configuration ==="
    # Check if local-lvm exists but is disabled
    if grep -q "lvmthin: local-lvm" /etc/pve/storage.cfg 2>/dev/null; then
        echo "local-lvm exists in config, checking status..."
        # Try to enable it
        pvesm set local-lvm --disable 0 2>&1 || echo "Could not enable via pvesm"
    else
        echo "local-lvm not in config, checking if we should add it..."
        # Check if pve/data thin pool exists
        if lvs pve/data 2>/dev/null | grep -q "data"; then
            echo "Found pve/data thin pool, adding local-lvm storage..."
            pvesm add lvmthin local-lvm \
                --thinpool pve/data \
                --vgname pve \
                --content images,rootdir \
                --nodes r630-01 2>&1 || echo "Failed to add local-lvm"
        fi
    fi
    
    # Check if thin1 exists and should be enabled
    if lvs pve/thin1 2>/dev/null | grep -q "thin1"; then
        echo "Found pve/thin1, checking if storage is configured..."
        if ! grep -q "lvmthin: thin1" /etc/pve/storage.cfg 2>/dev/null; then
            echo "Adding thin1 storage..."
            pvesm add lvmthin thin1 \
                --thinpool pve/thin1 \
                --vgname pve \
                --content images,rootdir \
                --nodes r630-01 2>&1 || echo "Failed to add thin1"
        else
            echo "thin1 exists, updating node reference..."
            # Update node reference from pve to r630-01
            sed -i 's/nodes pve$/nodes r630-01/' /etc/pve/storage.cfg 2>/dev/null || true
            sed -i 's/nodes pve /nodes r630-01 /' /etc/pve/storage.cfg 2>/dev/null || true
        fi
    fi
    
    echo ""
    echo "=== Updated Storage Status ==="
    pvesm status 2>/dev/null || echo "pvesm not available"
    echo ""
ENDSSH

# Fix r630-02 storage
log_section "Fixing r630-02 (${R630_02_IP}) Storage"

sshpass -p "$R630_02_PASS" ssh -o StrictHostKeyChecking=no root@"$R630_02_IP" bash <<'ENDSSH'
    echo "=== Current Storage Configuration ==="
    cat /etc/pve/storage.cfg 2>/dev/null | head -50
    echo ""
    
    echo "=== Current Volume Groups ==="
    vgs
    echo ""
    
    echo "=== Fixing Storage Node References ==="
    # Update all storage configs to use r630-02 instead of pve2
    if [ -f /etc/pve/storage.cfg ]; then
        cp /etc/pve/storage.cfg /etc/pve/storage.cfg.backup.$(date +%Y%m%d_%H%M%S)
        sed -i 's/nodes pve2$/nodes r630-02/' /etc/pve/storage.cfg 2>/dev/null || true
        sed -i 's/nodes pve2 /nodes r630-02 /' /etc/pve/storage.cfg 2>/dev/null || true
        echo "Updated storage.cfg node references"
    fi
    
    echo ""
    echo "=== Enabling Storage ==="
    # Enable all thin storage pools
    for storage in thin1 thin2 thin3 thin4 thin5 thin6; do
        if pvesm status "$storage" 2>/dev/null | grep -q "disabled"; then
            echo "Enabling $storage..."
            pvesm set "$storage" --disable 0 2>&1 || echo "Could not enable $storage"
        fi
    done
    
    # Check if local-lvm should be added
    if ! grep -q "lvmthin: local-lvm" /etc/pve/storage.cfg 2>/dev/null; then
        # Check which VG to use (probably thin1)
        if vgs thin1 >/dev/null 2>&1; then
            echo "Adding local-lvm using thin1 volume group..."
            # Find the thin pool in thin1
            thin_pool=$(lvs thin1 --noheadings -o lv_name 2>/dev/null | grep -E "thin1|data" | head -1 | tr -d ' ')
            if [ -n "$thin_pool" ]; then
                pvesm add lvmthin local-lvm \
                    --thinpool thin1/$thin_pool \
                    --vgname thin1 \
                    --content images,rootdir \
                    --nodes r630-02 2>&1 || echo "Failed to add local-lvm"
            fi
        fi
    fi
    
    echo ""
    echo "=== Updated Storage Status ==="
    pvesm status 2>/dev/null || echo "pvesm not available"
    echo ""
ENDSSH

log_section "Storage Fix Complete"
log_info "Verifying storage status..."

sshpass -p "$R630_01_PASS" ssh -o StrictHostKeyChecking=no root@"$R630_01_IP" "pvesm status 2>/dev/null | grep -E 'local-lvm|thin1'" || true
sshpass -p "$R630_02_PASS" ssh -o StrictHostKeyChecking=no root@"$R630_02_IP" "pvesm status 2>/dev/null | head -10" || true

log_success "Storage configuration fix complete!"
log_info "Review the output above and verify storage is now enabled."
