#!/bin/sh
# Begin $rc_base/init.d/checkfs - File System Check Script

# Based on checkfs script from LFS-3.1 and earlier.
# Rewritten by Gerard Beekmans  - gerard@linuxfromscratch.org
# Patch to handle all fsck variants by A. Luebke - luebke@users.sourceforge.net

# From man fsck
# 0    - No errors
# 1    - File system errors corrected
# 2    - System should be rebooted
# 4    - File system errors left uncorrected
# 8    - Operational error
# 16   - Usage or syntax error
# 32   - Fsck canceled by user request
# 128  - Shared library error

. /etc/sysconfig/rc
. $rc_functions

case "$1" in
	start)
		if [ -f /fastboot ]
		then
			echo "Fast boot requested, will not perform file system checks"
			exit 0
		fi

		echo "Mounting root file system in read-only mode..."
		mount -n -o remount,ro /
		evaluate_retval

		if [ $? != 0 ]
		then
			echo -n -e $FAILURE
			echo
			echo "Cannot check root file system because it could not"
			echo "be mounted in read-only mode."
			echo
			echo -n "When you press Enter, this system will be halted."
			echo -n -e $NORMAL
			echo
			echo "Press Enter to continue..."
			read ENTER
			halt -f
		fi

		if [ -f /forcefsck ]
		then
			echo "/forcefsck exists, forcing file system check"
			options="-f"
			else
			options=""
		fi

		echo "Checking file systems..."
		#Note: -a option used to be -p; but this fails e.g. on fsck.minix
		fsck $options -a -A -C -T
		error_value=$?

		if [ "$error_value" = 1 ]
		then
			echo -n -e $WARNING
			echo "File system errors were found and have been corrected."
			echo "You may want to double-check that everything was fixed"
			echo -n "properly"
			echo -n -e $NORMAL
			print_status warning
		fi

		if [ "$error_value" = 0 ]
		then
			print_status success
		fi

		if [ "$error_value" = 2 -o "$error_value" = 3 ]
		then
			echo -n -e $WARNING
			echo "File system errors were found and have been corrected, but"
			echo "the nature of the errors require this system to be rebooted."
			echo
			echo -n "When you press Enter, this system will be rebooted."
			echo -n -e $NORMAL
			print_status warning
			echo
			echo "Please Enter to continue..."
			read ENTER
			reboot -f
		fi

		if [ "$error_value" -gt 3 -a "$error_value" -lt 16 ]
		then
			echo -n -e $FAILURE
			echo "File system errors were encountered that couldn't be"
			echo "fixed automatically. This system cannot continue to boot"
			echo "and will therefore be halted until those errors fixed manually"
			echo "by a System Administrator."
			echo
			echo -n "When you press Enter, this system will be halted."
			echo -n -e $NORMAL
			print_status failure
			echo
			echo "Press Enter to continue..."
			read ENTER
			halt -f
		fi

		if [ "$error_value" -ge 16 ]
		then 
			echo -n -e $FAILURE
			echo "Unexpected Failure running fsck. Exited with "$error_value
			echo -n -e $NORMAL
			print_status failure
			exit $error_value
		fi
		;;
	*)
		echo "Usage: $0 {start}"
		exit 1
		;;
esac

# End $rc_base/init.d/checkfs
