#!/bin/sh
### BEGIN INIT INFO
# Provides:          fsck
# Required-Start:    udev
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Check all filesystems marked for fsck in /etc/fstab.
### END INIT INFO

# NB: this is the normal exit point, reached when the fsck process sends the TERM signal.
trap "exit 0" TERM	

export PID=$$

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin:/opt/RAYLASE/SPICE3/bin"

do_fsck()
{
	# Check all local filesystems marked for fsck in /etc/fstab on startup.
	test "$VERBOSE" != no && echo "Checking local filesystems..."

	# First check root fs
	# See if root fs is mounted rw, if yes it has to be remounted ro in order for fsck to work
	local rootRwFlag=`expr "$(cat /proc/mounts | grep rootfs)" : '^.*\([ ]rw[ ]\).*'$`
	local rootPart=`expr "$(cat /proc/cmdline | grep root)" : '^.*root=\([^ ]*\).*'$`
	test "$VERBOSE" != no && echo " rootRwFlag = '$rootRwFlag', rootPart = '$rootPart'"

	[ "$rootRwFlag" = "rw" ] && mount -n -o remount,ro /
	# Dry run
	fsck -n $rootPart
	if test "$?" -gt 1
	then
		# If an error was found force a repair and reboot
		test "$VERBOSE" != no && echo " repairing root filesystem..."
		fsck -pf $rootPart
		test "$VERBOSE" != no && echo " rebooting..."
		reboot -f
	fi

	# If remounted ro mount it back to rw
	[ "$rootRwFlag" = "rw" ] && mount -n -o remount,rw /

	# Check filesystems from type vfat
	test "$VERBOSE" != no && echo " checking vfat filesystems..."
	fsck -ATt vfat -aw
	## Check all remaining filesystems
	test "$VERBOSE" != no && echo " checking other filesystems..."
	fsck -ATRt novfat -p

	kill -s TERM $PID
	exit 0
}

# Execute fsck in a separate background process.
do_fsck &

# As long as fsck is active, we need to trigger the watchdog.
# We stop triggering when the TERM signal is sent from fsck subroutine after the fsck command has finished.
# After 180s we stop triggering the watchdog on the assuption that fsck failed or got stuck.
n=0
while [ $n -le 18 ]
do
	sleep 10

	#
	# If we reach this point, the fsck command has alomst certainly discovered a problem with the FS.
	# We need to trigger the WD, but this will also cause it to switch to the shorter standard timeout period (11s) set by U-Boot.
	# Since some of the subsequent init-scripts are know to need more than 11s runtime, we deliberately re-program the WD period before triggering.
	# In the "spice3" init-script we change the period back once again to 11s.
	#
	# Set WD timeout for retriggers = (1 << (15+16)) / 25 MHz = 88 seconds: Value F
	rawmem32 0xffd03004 0xff >/dev/null

	echo "Triggering watchdog while waiting for fsck to finish..."
	rawmem32 0xffd0300c 0x76 >/dev/null
	n=$(( n+1 ))
done

# This is the ABnormal exit point!
exit 1

