# create makes exactly what it advertises.

exits 0 "create makes a VM" create cr1 64M
holds "create makes the disk it advertises" test -f "$VMMDIR/cr1/disk.qcow2"
holds "create writes a uuid" test -s "$VMMDIR/cr1/uuid"
holds "create writes no configurable primary disk path" \
	test -z "$(grep '^IMAGE=' "$VMMDIR/cr1/config" || :)"
exits 1 "create refuses an existing VM" create cr1 64M

# shellcheck disable=SC2012  # the path is vmm's own and fixed, not user input
perm=$(ls -ld "$VMMDIR/cr1" | cut -c1-10)
if [ "$perm" = drwx------ ]; then
	ok "VM directory is 0700"
else
	notok "VM directory is 0700" "got $perm"
fi

# The directory is the only authentication the monitor has, so every
# file in it is 0600. ls is the whole check: awk lists any regular file
# or FIFO whose mode is anything else.
# shellcheck disable=SC2012  # the names are vmm's own, not user input
bad=$(ls -l "$VMMDIR/cr1" | awk '$1 ~ /^[-p]/ && $1 !~ /^[-p]rw-------$/ { print $NF }')
if [ -z "$bad" ]; then
	ok "every file create writes is 0600"
else
	notok "every file create writes is 0600" "$bad"
fi

# Validation happens before mkdir. Later failures leave their work visible.
exits 1 "create refuses a malformed size" create cr2 10GG
holds "a refused create leaves nothing behind" test ! -e "$VMMDIR/cr2"
exits 1 "create refuses a zero-sized disk" create cr2 0
exits 1 "create refuses a zero with a suffix" create cr2 00G
exits 1 "create refuses a leading zero" create cr2 01G
exits 1 "create fails when qemu-img refuses the size" create cr3 99999999999999999999G
holds "a failed qemu-img leaves an incomplete directory" \
	test -d "$VMMDIR/cr3"
holds "a failed qemu-img does not commit a config" \
	test ! -e "$VMMDIR/cr3/config"

# A directory without config is not guessed at or recovered automatically.
mkdir "$VMMDIR/cr4"
printf 'partial\n' > "$VMMDIR/cr4/junk"
exits 1 "create refuses an incomplete directory" create cr4 64M
holds "an incomplete directory remains untouched" \
	test -f "$VMMDIR/cr4/junk"
unlink "$VMMDIR/cr4/junk"
rmdir "$VMMDIR/cr4"
