#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2018 Huawei.  All Rights Reserved.
#
# FS QA Test 507
#
# This testcase is trying to test recovery flow of generic filesystem, w/ below
# steps, once i_flags changes, after we fsync that file, we can expect that
# i_flags can be recovered after sudden power-cuts.
# 1. touch testfile;
# 1.1 sync (optional)
# 2. chattr +[ASai] testfile
# 3. xfs_io -f testfile -c "fsync";
# 4. godown;
# 5. umount;
# 6. mount;
# 7. check i_flags
# 8. chattr -[ASai] testfile
# 9. xfs_io -f testfile -c "fsync";
# 10. godown;
# 11. umount;
# 12. mount;
# 13. check i_flags
#
. ./common/preamble
_begin_fstest shutdown auto quick metadata

# Override the default cleanup function.
_cleanup()
{
	cd /
	$CHATTR_PROG -ai $testfile &> /dev/null
	rm -f $tmp.*
}

# Import common functions.
. ./common/filter


_require_command "$LSATTR_PROG" lasttr
_require_command "$CHATTR_PROG" chattr
_require_chattr ASai

_require_scratch
_require_scratch_shutdown

_scratch_mkfs >/dev/null 2>&1
_require_metadata_journaling $SCRATCH_DEV

testfile=$SCRATCH_MNT/testfile

do_check()
{
	attr=$1

	_scratch_mount

	touch $testfile

	if [ "$2" == "sync" ]; then
		echo "sync" >> $seqres.full
		_scratch_sync
	fi

	echo "Test chattr +$1" >> $seqres.full

	# add attribute
	$CHATTR_PROG +$attr $testfile

	before=`$LSATTR_PROG $testfile`

	$XFS_IO_PROG -r -f $testfile -c "fsync" | _filter_xfs_io

	_scratch_shutdown | tee -a $seqres.full
	_scratch_cycle_mount

	after=`$LSATTR_PROG $testfile`

	# check inode's i_flags
	if [ "$before" != "$after" ]; then
		echo "Before: $before"
		echo "After : $after"
	fi
	echo "Before: $before" >> $seqres.full
	echo "After : $after" >> $seqres.full

	echo "Test chattr -$1" >> $seqres.full

	# delete attribute
	$CHATTR_PROG -$attr $testfile

	before=`$LSATTR_PROG $testfile`

	$XFS_IO_PROG -r -f $testfile -c "fsync" | _filter_xfs_io

	_scratch_shutdown | tee -a $seqres.full
	_scratch_cycle_mount

	after=`$LSATTR_PROG $testfile`

	# check inode's i_flags
	if [ "$before" != "$after" ]; then
		echo "Before: $before"
		echo "After : $after"
	fi
	echo "Before: $before" >> $seqres.full
	echo "After : $after" >> $seqres.full

	rm -f $testfile
	_scratch_unmount
}

echo "Silence is golden"

opts="A S a i"
for i in $opts; do
	do_check $i
	do_check $i sync
done

status=0
exit
