#!/usr/bin/env bash
# Migrate 2 containers to pve2 thin1 storage using backup/restore method
# This is the reliable way when pct migrate doesn't support storage selection

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_container() {
    local vmid=$1
    local name=$2
    
    log_info "========================================="
    log_info "Migrating container $vmid ($name)"
    log_info "========================================="
    
    # Step 1: Create backup on source node
    log_info "Step 1: Creating backup of container $vmid on $SOURCE_NODE..."
    
    backup_dir="/tmp/migrations"
    ssh_proxmox "mkdir -p $backup_dir"
    
    # Create backup (to local storage on source node)
    log_info "  Running vzdump backup (this may take a few minutes)..."
    if ssh_proxmox "vzdump $vmid --compress zstd --storage local --dumpdir $backup_dir --mode snapshot" 2>&1 | tee /tmp/vzdump-${vmid}.log; then
        log_success "  Backup completed"
        
        # Find the backup file
        backup_file=$(ssh_proxmox "ls -t $backup_dir/vzdump-lxc-${vmid}-*.tar.zst 2>/dev/null | head -1")
        if [[ -z "$backup_file" ]]; then
            log_error "  Could not find backup file"
            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..."
    log_info "  This will create the container on pve2 using thin1 storage"
    
    # Use vzrestore which supports --storage parameter
    if ssh_proxmox "vzrestore $backup_file $vmid --storage $TARGET_STORAGE" 2>&1 | tee /tmp/vzrestore-${vmid}.log; then
        log_success "  Container restored on $TARGET_NODE with $TARGET_STORAGE storage"
    else
        log_error "  Restore failed"
        log_info "  Trying alternative restore method..."
        
        # Alternative: use pct restore
        if ssh_proxmox "pct restore $vmid $backup_file --storage $TARGET_STORAGE" 2>&1 | tee /tmp/pct-restore-${vmid}.log; then
            log_success "  Container restored using pct restore"
        else
            log_error "  All restore methods failed"
            return 1
        fi
    fi
    
    # Step 3: Start container
    log_info "Step 3: Starting container on $TARGET_NODE..."
    ssh_proxmox "pct start $vmid --target $TARGET_NODE" 2>&1 || ssh_proxmox "pct start $vmid" 2>&1
    sleep 3
    
    # Step 4: Verify
    log_info "Step 4: Verifying migration..."
    target_status=$(ssh_proxmox "pvesh get /nodes/$TARGET_NODE/lxc/$vmid/status/current --output-format json" 2>&1 | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('status', 'unknown'))" 2>/dev/null || echo "unknown")
    
    if [[ "$target_status" != "unknown" ]]; then
        log_success "  Container is running on $TARGET_NODE (status: $target_status)"
        
        # Verify storage
        storage=$(ssh_proxmox "pvesh get /nodes/$TARGET_NODE/lxc/$vmid/config --output-format json" 2>&1 | python3 -c "import sys, json; d=json.load(sys.stdin); rootfs=d.get('rootfs', ''); print(rootfs.split(':')[0] if ':' in rootfs else 'unknown')" 2>/dev/null || echo "unknown")
        if [[ "$storage" == "$TARGET_STORAGE" ]]; then
            log_success "  Container is using $TARGET_STORAGE storage ✓"
        else
            log_warn "  Container storage is $storage (expected $TARGET_STORAGE)"
        fi
        
        # Step 5: Optionally remove original (commented out for safety)
        log_warn "  Original container still exists on $SOURCE_NODE"
        log_info "  After verifying, you can remove it with: pct destroy $vmid (on $SOURCE_NODE)"
        
        return 0
    else
        log_error "  Verification failed - container status unknown"
        return 1
    fi
}

# Main
main() {
    echo "========================================="
    echo "Migrate 2 containers to pve2 thin1"
    echo "Using backup/restore method"
    echo "========================================="
    echo ""
    
    CONTAINERS=(
        "1500:besu-sentry-1"
        "1501:besu-sentry-2"
    )
    
    failed=0
    success=0
    
    for container in "${CONTAINERS[@]}"; do
        vmid="${container%%:*}"
        name="${container#*:}"
        
        if migrate_container "$vmid" "$name"; then
            success=$((success + 1))
        else
            failed=$((failed + 1))
        fi
        
        echo ""
        if [[ $success -lt ${#CONTAINERS[@]} ]]; then
            log_info "Waiting 10 seconds before next container..."
            sleep 10
        fi
    done
    
    echo ""
    echo "========================================="
    log_info "Migration Summary: $success/${#CONTAINERS[@]} successful, $failed failed"
    echo "========================================="
}

main "$@"

