#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2025 SUSE S.A.  All Rights Reserved.
#
# FS QA Test 785
#
# Test that if we fsync a file, create a directory in the same parent directory
# of the file, add a file to the new directory, rename the initial file and then
# fsync the parent directory of the first file, after a power failure the new
# directory exists, with its new entry and the first file has the new name and
# any data we wrote to it before its fsync.
#
. ./common/preamble
_begin_fstest auto quick log

_cleanup()
{
	_cleanup_flakey
	cd /
	rm -r -f $tmp.*
}

. ./common/filter
. ./common/dmflakey

_require_scratch
_require_dm_target flakey
_require_fssum

_fixed_by_fs_commit btrfs 5630f7557de6 \
	"btrfs: do not skip logging new dentries when logging a new name"

_scratch_mkfs >>$seqres.full 2>&1 || _fail "mkfs failed"
_require_metadata_journaling $SCRATCH_DEV
_init_flakey
_scratch_mount

# Create our first test file.
echo -n > $SCRATCH_MNT/file1

# Persist the file and commit the current transaction.
_scratch_sync

# Change the file (by writing some data to it for example) and fsync it.
$XFS_IO_PROG -c "pwrite -S 0xab 0 1000" \
	     -c "fsync" $SCRATCH_MNT/file1 | _filter_xfs_io

# Create a new directory in the same parent directory as the previous file.
mkdir $SCRATCH_MNT/dir
# Add a new file to this new directory.
echo -n > $SCRATCH_MNT/dir/foo

# Rename the first file, but keeping it in the same parent directory.
mv $SCRATCH_MNT/file1 $SCRATCH_MNT/file2

# Fsync the parent directory of the first file.
$XFS_IO_PROG -c "fsync" $SCRATCH_MNT/

# Create a digest of the filesystem's content.
$FSSUM_PROG -A -f -w $tmp.fssum $SCRATCH_MNT/

# Simulate a power failure and then mount again the filesystem to replay the
# journal/log.
_flakey_drop_and_remount

# Verify the filesystem has the same content that it had right before the power
# failure and after the last fsync.
$FSSUM_PROG -r $tmp.fssum $SCRATCH_MNT/

_scratch_unmount

# success, all done
_exit 0
