# clone and delete.

"$VMM" create cl1 64M >/dev/null 2>&1
cfg cl1 <<EOF
HOSTFWD="2222:22"
EOF

exits 0 "clone copies a stopped VM" clone cl1 cl2
holds "clone copies config byte for byte" \
	cmp -s "$VMMDIR/cl1/config" "$VMMDIR/cl2/config"
holds "clone owns a separate fixed disk" \
	test -f "$VMMDIR/cl2/disk.qcow2"
holds "clone copies the source disk contents" \
	cmp -s "$VMMDIR/cl1/disk.qcow2" "$VMMDIR/cl2/disk.qcow2"
holds "clone gets a new uuid" \
	test "$(cat "$VMMDIR/cl1/uuid")" != "$(cat "$VMMDIR/cl2/uuid")"
# The uuid feeds the MAC, so a copy that kept either would collide with
# its source on the first network it joined.
m1=$("$VMM" dryrun cl1 2>/dev/null | sed -n 's/.*mac=\([0-9a-f:]*\).*/\1/p')
m2=$("$VMM" dryrun cl2 2>/dev/null | sed -n 's/.*mac=\([0-9a-f:]*\).*/\1/p')
holds "the clone's MAC differs from its source's" \
	test -n "$m1" -a "$m1" != "$m2"

exits 1 "clone refuses an existing destination" clone cl1 cl2

# Copy failures leave an incomplete destination without committing config.
mv "$VMMDIR/cl1/disk.qcow2" "$WORK/cl1.qcow2"
exits 1 "clone reports a disk copy failure" clone cl1 clf
holds "a failed clone leaves an incomplete directory" test -d "$VMMDIR/clf"
holds "a failed clone does not commit a config" test ! -e "$VMMDIR/clf/config"
mv "$WORK/cl1.qcow2" "$VMMDIR/cl1/disk.qcow2"

# A partial destination is preserved for manual inspection.
mkdir -p "$VMMDIR/clx"
printf 'partial\n' > "$VMMDIR/clx/junk"
exits 1 "clone refuses an incomplete destination" clone cl1 clx
holds "the refused clone leaves the partial contents alone" \
	test -f "$VMMDIR/clx/junk"
unlink "$VMMDIR/clx/junk"
rmdir "$VMMDIR/clx"

exits 0 "delete -f removes a stopped VM" delete -f cl2
holds "delete really removes the directory" test ! -e "$VMMDIR/cl2"
holds "deleting a clone leaves the source disk alone" \
	test -f "$VMMDIR/cl1/disk.qcow2"
exits 1 "delete without -f and without a tty refuses" delete cl1
