#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2025 SUSE S.A.  All Rights Reserved.
#
# FS QA Test 779
#
# Test that if we fsync a directory that has a new symlink, then rename the
# symlink and fsync again the directory, after a power failure the symlink
# exists with the new name and not the old one.
#
. ./common/preamble
_begin_fstest auto quick log

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

. ./common/dmflakey

_require_scratch
_require_symlinks
_require_dm_target flakey

[ "$FSTYP" = "btrfs" ] && _fixed_by_kernel_commit xxxxxxxxxxxx \
	"btrfs: set inode flag BTRFS_INODE_COPY_EVERYTHING when logging new name"

rm -f $seqres.full

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

# Create our test dir and add a symlink inside it.
mkdir $SCRATCH_MNT/dir
ln -s foobar $SCRATCH_MNT/dir/old-slink

# Fsync the test dir, should persist the symlink.
$XFS_IO_PROG -c "fsync" $SCRATCH_MNT/dir

# Rename the symlink and fsync the directory. It should persist the new symlink
# name.
mv $SCRATCH_MNT/dir/old-slink $SCRATCH_MNT/dir/new-slink
$XFS_IO_PROG -c "fsync" $SCRATCH_MNT/dir

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

# Check that the symlink exists with the new name and has the correct content.
[ -L $SCRATCH_MNT/dir/new-slink ] || echo "symlink dir/new-slink not found"
echo "symlink content: $(readlink $SCRATCH_MNT/dir/new-slink)"

_unmount_flakey

# success, all done
_exit 0
