#!/usr/bin/env bash
# Enable and configure local-lvm storage on pve and pve2 for migrations

set -euo pipefail

PROXMOX_HOST_PVE="192.168.11.11"
PROXMOX_HOST_PVE2="192.168.11.12"
PVE_PASS="password"
STORAGE_NAME="local-lvm"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check and fix storage on a node
fix_storage() {
    local host=$1
    local node_name=$2
    
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Processing: $node_name ($host)"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    # Get storage config
    local storage_cfg=$(sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} \
        "cat /etc/pve/storage.cfg 2>/dev/null | grep -A 10 '${STORAGE_NAME}'" || echo "")
    
    if [ -z "$storage_cfg" ]; then
        log_warn "Storage $STORAGE_NAME not found in config. May need to be added."
    else
        log_info "Current storage configuration:"
        echo "$storage_cfg"
        echo ""
    fi
    
    # Check volume groups
    log_info "Available volume groups:"
    sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} "vgs 2>/dev/null" || true
    echo ""
    
    # Find appropriate VG and thin pool
    local vg_name=$(sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} \
        "vgs --noheadings -o vg_name 2>/dev/null | head -1" | tr -d ' ')
    
    if [ -z "$vg_name" ]; then
        log_error "No volume groups found on $node_name"
        return 1
    fi
    
    log_info "Using volume group: $vg_name"
    
    # Find thin pool (look for data or similar)
    local thin_pool=$(sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} \
        "lvs $vg_name --noheadings -o lv_name 2>/dev/null | grep -E '(data|thin)' | head -1" | tr -d ' ')
    
    if [ -z "$thin_pool" ]; then
        log_warn "No suitable thin pool found. Need to create one."
        log_info "Checking available space in $vg_name..."
        local vg_free=$(sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} \
            "vgs -o vg_free --noheadings --units g $vg_name 2>/dev/null | awk '{print int(\$1)}'" || echo "0")
        log_info "Free space: ${vg_free}G"
        
        if [ "$vg_free" -lt 10 ]; then
            log_error "Not enough free space to create thin pool"
            return 1
        fi
        
        # Try to create thin pool named 'data'
        log_info "Creating thin pool 'data' in $vg_name..."
        sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} <<EOF
lvcreate -L \$((vg_free * 80 / 100))G -n data $vg_name 2>&1 || true
lvconvert --type thin-pool $vg_name/data 2>&1 || true
EOF
        thin_pool="data"
    else
        log_success "Found thin pool: $vg_name/$thin_pool"
    fi
    
    # Check if storage is enabled
    local storage_status=$(sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} \
        "pvesm status $STORAGE_NAME 2>/dev/null | awk '{print \$2}'" || echo "not_found")
    
    if [ "$storage_status" = "not_found" ]; then
        log_info "Storage not found, adding to Proxmox..."
        sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} <<EOF
pvesm add lvmthin $STORAGE_NAME \
    --thinpool ${vg_name}/${thin_pool} \
    --content images,rootdir \
    --nodes ${host} 2>&1
EOF
    elif [ "$storage_status" = "0" ] || [ "$storage_status" = "disabled" ]; then
        log_info "Storage exists but may be disabled. Checking configuration..."
        
        # Try to update storage config
        sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} <<EOF
pvesm set $STORAGE_NAME --content images,rootdir 2>&1 || true
pvesm status $STORAGE_NAME 2>&1
EOF
    else
        log_success "Storage is active"
    fi
    
    # Verify final status
    log_info "Final storage status:"
    sshpass -p "$PVE_PASS" ssh -o StrictHostKeyChecking=accept-new root@${host} \
        "pvesm status $STORAGE_NAME 2>&1" || true
    echo ""
    
    return 0
}

# Main execution
main() {
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Enable local-lvm Storage for Migrations"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    # Process pve
    if sshpass -p "$PVE_PASS" ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new root@${PROXMOX_HOST_PVE} "echo 'connected'" 2>/dev/null; then
        fix_storage "$PROXMOX_HOST_PVE" "pve"
    else
        log_error "Cannot connect to pve"
    fi
    
    # Process pve2
    if sshpass -p "$PVE_PASS" ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=accept-new root@${PROXMOX_HOST_PVE2} "echo 'connected'" 2>/dev/null; then
        fix_storage "$PROXMOX_HOST_PVE2" "pve2"
    else
        log_warn "Cannot connect to pve2, skipping..."
    fi
    
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Summary"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    log_info "Storage configuration complete. You can now attempt"
    log_info "container migrations from ml110 to pve/pve2."
    echo ""
}

main "$@"

