#!/bin/bash
# qemu-ram - run a qcow2 VM fully in RAM
# usage: ./qemu-ram [disk.qcow2]

set -e

DISK="${1:-disk.qcow2}"       # default se non passi nulla
RAMDISK="/dev/shm/$(basename "$DISK")"

if [ ! -f "$DISK" ]; then
  echo "❌ Disk not found: $DISK"
  exit 1
fi

# copy qcow2 into RAM
echo "📥 Copying $DISK into RAM..."
cp "$DISK" "$RAMDISK"

# run QEMU from RAM copy
echo "🚀 Starting VM from $RAMDISK"
qemu-system-x86_64 \
  -enable-kvm -m 4096 -smp 4 \
  -drive file="$RAMDISK",format=qcow2 \
  -nic user,model=virtio \
  -display gtk

# after VM exit
echo
read -p "💾 Sync changes back to disk? [y/N] " ans
if [[ "$ans" =~ ^[Yy]$ ]]; then
  cp "$DISK" "${DISK}.bak"
  echo "💾 Saving RAM copy as new $DISK"
  rsync -a --inplace "$RAMDISK" "$DISK"
  echo "✅ Sync complete"
else
  echo "❌ Changes discarded"
fi

rm -f "$RAMDISK"
echo "🧹 RAM cleaned"
