#!/bin/bash
# Migrate VMIDs 100-130 and 7800-7811 using backup/restore with dumpdir
# VMIDs 100-130 → thin1 storage on r630-01
# VMIDs 7800-7811 → local storage on r630-01

set -euo pipefail

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

SOURCE_NODE="r630-02"
TARGET_NODE="r630-01"
DUMPDIR="/var/lib/vz/dump"

VMIDS_100_130=(100 101 102 103 104 105 130)
VMIDS_7800_7811=(7800 7801 7802 7810 7811)

ALL_VMIDS=("${VMIDS_100_130[@]}" "${VMIDS_7800_7811[@]}")

log_section "VM Migration to r630-01 (Backup/Restore Method)"

FAILED=()
SUCCESS=()

# Function to migrate a single VM
migrate_vm() {
    local vmid=$1
    local target_storage=$2
    
    log_info "Processing VMID $vmid..."
    
    # Check if VM exists on source
    if ! sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.12 \
        "pct list 2>/dev/null | grep -q \"^$vmid\"" 2>/dev/null; then
        log_warn "VMID $vmid not found on source, skipping"
        return 1
    fi
    
    # Check if already on target
    if sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.11 \
        "pct list 2>/dev/null | grep -q \"^$vmid\"" 2>/dev/null; then
        log_warn "VMID $vmid already on target, skipping"
        return 0
    fi
    
    # Step 1: Create backup using dumpdir (bypasses storage config)
    log_info "  Creating backup..."
    BACKUP_OUTPUT=$(sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.12 \
        "vzdump $vmid --dumpdir $DUMPDIR --compress gzip --mode stop 2>&1")
    
    if [ $? -ne 0 ]; then
        log_error "  Backup failed for VMID $vmid"
        echo "$BACKUP_OUTPUT" | tail -5
        return 1
    fi
    
    # Find backup file
    BACKUP_FILE=$(sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.12 \
        "ls -t $DUMPDIR/vzdump-lxc-$vmid-*.tar.gz 2>/dev/null | head -1" 2>/dev/null)
    
    if [ -z "$BACKUP_FILE" ]; then
        log_error "  Backup file not found for VMID $vmid"
        return 1
    fi
    
    BACKUP_SIZE=$(sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.12 \
        "du -h $BACKUP_FILE 2>/dev/null | cut -f1" 2>/dev/null)
    log_info "  Backup created: $(basename $BACKUP_FILE) ($BACKUP_SIZE)"
    
    # Step 2: Restore on target
    log_info "  Restoring to $TARGET_NODE (storage: $target_storage)..."
    RESTORE_OUTPUT=$(sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.12 \
        "pct restore $vmid $BACKUP_FILE --storage $target_storage --target $TARGET_NODE 2>&1")
    
    if [ $? -eq 0 ]; then
        log_success "  VMID $vmid migrated successfully"
        
        # Step 3: Verify on target
        sleep 3
        if sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.11 \
            "pct list 2>/dev/null | grep -q \"^$vmid\"" 2>/dev/null; then
            log_success "  Verified VMID $vmid on $TARGET_NODE"
            
            # Step 4: Remove from source
            log_info "  Removing from source node..."
            sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.12 \
                "pct destroy $vmid 2>&1" || log_warn "  Failed to remove from source"
            
            return 0
        else
            log_warn "  Migration completed but VM not yet visible on target"
            return 0
        fi
    else
        log_error "  Restore failed for VMID $vmid"
        echo "$RESTORE_OUTPUT" | tail -5
        return 1
    fi
}

# Migrate VMIDs 100-130 to thin1
log_section "Migrating VMIDs 100-130 to thin1 storage"

for vmid in "${VMIDS_100_130[@]}"; do
    if migrate_vm $vmid "thin1"; then
        SUCCESS+=($vmid)
    else
        FAILED+=($vmid)
    fi
    echo ""
done

# Migrate VMIDs 7800-7811 to local storage
log_section "Migrating VMIDs 7800-7811 to local storage"

for vmid in "${VMIDS_7800_7811[@]}"; do
    if migrate_vm $vmid "local"; then
        SUCCESS+=($vmid)
    else
        FAILED+=($vmid)
    fi
    echo ""
done

# Summary
log_section "Migration Summary"

log_info "Successful migrations: ${#SUCCESS[@]}/${#ALL_VMIDS[@]}"
if [ ${#SUCCESS[@]} -gt 0 ]; then
    echo "  VMIDs: ${SUCCESS[*]}"
fi

if [ ${#FAILED[@]} -gt 0 ]; then
    log_warn "Failed migrations: ${#FAILED[@]}"
    echo "  VMIDs: ${FAILED[*]}"
fi

log_section "Verification"

log_info "VMs on $TARGET_NODE:"
sshpass -p "password" ssh -o StrictHostKeyChecking=no root@192.168.11.11 \
    "pct list 2>/dev/null | grep -E '$(IFS='|'; echo "${ALL_VMIDS[*]}")'" 2>/dev/null || true

log_section "Complete"

if [ ${#FAILED[@]} -eq 0 ]; then
    log_success "All VMs migrated successfully!"
    exit 0
else
    log_warn "Some migrations failed. Please review errors above."
    exit 1
fi
