#!/usr/bin/env bash
# Migrate 2 containers to pve2 using thin1 storage via backup/restore method
# This approach allows us to specify target storage

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
PROXMOX_PASS="${PROXMOX_PASS:-L@kers2010}"
SOURCE_NODE="ml110"
TARGET_NODE="pve2"
TARGET_STORAGE="thin1"

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

ssh_proxmox() {
    sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "$@"
}

# Migrate container via backup/restore
migrate_via_backup() {
    local vmid=$1
    local name=$2
    
    log_info "Migrating container $vmid ($name) to $TARGET_NODE using $TARGET_STORAGE..."
    
    # Step 1: Create backup on source node
    log_info "  Step 1: Creating backup of container $vmid..."
    backup_file="/tmp/vzdump-lxc-${vmid}-$(date +%Y_%m_%d_%H_%M_%S).tar.zst"
    
    if ssh_proxmox "vzdump $vmid --compress zstd --storage local --dumpdir /tmp --remove 0" 2>&1 | tee /tmp/backup-${vmid}.log; then
        log_success "  Backup created"
        
        # Find backup file
        backup_file=$(ssh_proxmox "ls -t /tmp/vzdump-lxc-${vmid}-*.tar.zst 2>/dev/null | head -1")
        if [[ -z "$backup_file" ]]; then
            log_error "  Backup file not found"
            return 1
        fi
        log_info "  Backup file: $backup_file"
    else
        log_error "  Backup failed"
        return 1
    fi
    
    # Step 2: Restore on target node with thin1 storage
    log_info "  Step 2: Restoring container on $TARGET_NODE with $TARGET_STORAGE storage..."
    
    if ssh_proxmox "vzdump --storage $TARGET_STORAGE --ostype unmanaged $vmid $backup_file" 2>&1; then
        log_success "  Container restored on $TARGET_NODE"
    else
        log_error "  Restore failed"
        return 1
    fi
    
    # Step 3: Remove original container (optional - ask user)
    log_warn "  Original container still exists on $SOURCE_NODE"
    log_info "  You may want to remove it after verifying the migration"
    
    return 0
}

echo "========================================="
echo "Migrate 2 containers via backup/restore"
echo "========================================="
echo ""

CONTAINERS=(
    "1500:besu-sentry-1"
    "1501:besu-sentry-2"
)

for container in "${CONTAINERS[@]}"; do
    vmid="${container%%:*}"
    name="${container#*:}"
    
    echo ""
    migrate_via_backup "$vmid" "$name"
    echo ""
done

echo "Migration complete!"

