#!/bin/bash -

# Try turning lazy_refcounts on or off here.
options='compat=1.1,backing_fmt=raw,lazy_refcounts=on'
#options='compat=1.1,backing_fmt=raw'

# Try using direct qemu or via libvirt or distro default.
#export LIBGUESTFS_BACKEND=direct
#export LIBGUESTFS_BACKEND=libvirt

cd /tmp
rm -f test1.img
killall qemu-nbd

set -x
set -e

# Create test filesystem (test1.img).
guestfish -N fs exit

# Serve it over nbd.
qemu-nbd -r -t -f raw test1.img &
sleep 2

# Create overlay.
qemu-img create -f qcow2 -b nbd:localhost:10809 -o $options overlay.qcow2

# Write stuff to the overlay.
guestfish <<EOF
  add-drive overlay.qcow2 format:qcow2 cachemode:unsafe
  run
  mount /dev/sda1 /
  fill 1 90M /test
EOF

# Check overlay still has a backing file.
qemu-img info overlay.qcow2

killall qemu-nbd
