#!/bin/bash

# Check if correct number of arguments is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <vmid>"
    exit 1
fi

vmid=$1
source_storage="local-lvm"
target_storage="ssd2"

# Get container disk size
disk_size=$(pct config $vmid | grep "rootfs:" | awk -F ',' '{print $2}' | awk -F '=' '{print $2}')

if [ -z "$disk_size" ]; then
    echo "Error: Could not determine disk size for VMID $vmid."
    exit 1
fi

# Stop the container
pct stop $vmid

# Create a new volume on the target storage
pvesm alloc $target_storage $vmid vm-$vmid-disk-0 $disk_size

# Mount the new disk
mkdir -p /mnt/pve/$target_storage/$vmid
mount /dev/$target_storage/vm-$vmid-disk-0 /mnt/pve/$target_storage/$vmid

# Copy data
rsync -aHAX --progress /var/lib/lxc/$vmid/ /mnt/pve/$target_storage/$vmid/

# Unmount the new disk
umount /mnt/pve/$target_storage/$vmid

# Update LXC config
sed -i "s|$source_storage:vm-$vmid-disk-0|$target_storage:vm-$vmid-disk-0|" /etc/pve/lxc/$vmid.conf

# Start the container
pct start $vmid

# Cleanup: Remove old storage
pvesm free $source_storage:vm-$vmid-disk-0
lvremove -y /dev/$source_storage/vm-$vmid-disk-0

echo "LXC container $vmid has been moved from $source_storage to $target_storage successfully, and the old disk has been removed."
