# VFS-mutation syscalls (brintos/linux#5): mkdirat / chmod / chown / rename / fsync.
# These returned ENOSYS before the wasm32 kernel wired them. GNU `mv` masks a
# broken rename (copy-then-delete fallback) and no shell tool calls fsync, so the
# syscalls are exercised at the C boundary by the data/vfs-probe payload, which
# prints one `VFS-<name> OK|FAIL` line each. data payloads install 0644; the wasm
# exec bit is set on a private copy (chmod itself is one of the wired syscalls).
#
# The probe runs twice, against both filesystems the image has, because they do
# not behave alike: /tmp is a tmpfs, the rootfs is the cloud virtio-fs. Only the
# tmpfs pass ran until BRINTOS-52, which is why a virtio-fs rename defect reached
# the image with this suite green.
. "$BST_LIB"

probe=${TMPDIR:-/tmp}/bst-vfs-probe.$$
cp "$BST_DATA/vfs-probe" "$probe" 2>/dev/null && chmod +x "$probe" 2>/dev/null || {
  bst_notok vfs/stage "cannot stage $BST_DATA/vfs-probe"; exit 0; }

out=$("$probe" 2>&1)

# One assertion per ticket syscall. The four wired upstream must pass; chown is a
# known upstream gap (brintos/linux#5: no ownership model on the virtio-fs backend)
# and reports its actual state so a future wiring flips this suite green.
check_out vfs/mkdirat "VFS-mkdirat OK" printf '%s\n' "$out"
check_out vfs/fsync   "VFS-fsync OK"   printf '%s\n' "$out"
check_out vfs/chmod   "VFS-chmod OK"   printf '%s\n' "$out"
check_out vfs/rename  "VFS-rename OK"  printf '%s\n' "$out"
check_out vfs/chown   "VFS-chown OK"   printf '%s\n' "$out"

# rename onto an EXISTING file — the write-.new-then-rename atomic update every
# database-ish writer uses. Covered on the tmpfs first.
check_out vfs/rename-over "VFS-rename-over OK" printf '%s\n' "$out"

# --- the same probe against the rootfs (cloud virtio-fs) ----------------------
# The rootfs is read-only on an anonymously-booted session, which is the normal
# case: skip rather than fail, since an absent capability is not a defect. An
# owner-authenticated session makes it writable and the cases below run for real.
vdir=/var/lib/bst-vfs
if mkdir -p "$vdir" 2>/dev/null; then
  vout=$("$probe" /var/lib -vfs 2>&1)
  rmdir "$vdir" 2>/dev/null
  check_out vfs/rename-vfs      "VFS-rename-vfs OK"      printf '%s\n' "$vout"
  check_out vfs/rename-over-vfs "VFS-rename-over-vfs OK" printf '%s\n' "$vout"
else
  bst_skip vfs/rename-vfs      "rootfs read-only (anonymous session); needs an owner-authenticated boot"
  bst_skip vfs/rename-over-vfs "rootfs read-only (anonymous session); needs an owner-authenticated boot"
fi

rm -f "$probe"
