#!/bin/sh

export PATH=$PATH:/usr/sbin

# We need /proc for this to work
/bin/mount -t proc proc /proc

# Just to make sure, it *should* be mounted read-only
/bin/mount -o remount,ro /

# And /tmp
/bin/mount /tmp

echolcd "Setting time from hardware clock"

# First set the time correctly
# Work around a rather weird bug in the ds1337 driver....
# The first access after reboot gives some really funky results
cat /proc/ds1337 > /dev/null

YEAR=$(cat /proc/ds1337 | cut -c 7-8)
if [ $YEAR -le 99 -a $YEAR -gt 70 ]; then
	YEAR="19$YEAR"
else
	YEAR="20$YEAR"
fi

MONTH=$(cat /proc/ds1337 | cut -c 4-5)
DAY=$(cat /proc/ds1337 | cut -c 1-2)
HOUR=$(cat /proc/ds1337 | cut -c 9-10)
# Remove the leading 0 from the hour, if needed
# otherwise the math interpreter might not understand
# the number
if [ $HOUR -lt 10 ]; then
	HOUR=$(echo $HOUR | cut -c 2)
fi
# Add 1 to the hour
HOUR=$(printf "%02d" $((HOUR)))

MINUTE=$(cat /proc/ds1337 | cut -c 12-13)
SECOND=$(cat /proc/ds1337 | cut -c 15-16)

if [ -e /etc/TZ ]; then
        export TZ=`cat /etc/TZ`
fi

date $MONTH$DAY$HOUR$MINUTE$YEAR.$SECOND

echolcd "$(date +%F' '%T)"

sleep 1

#cat /proc/partitions | fgrep part | cut -c 23- | while read LINE
grep ext[23] /etc/fstab | while read LINE
do
	DEVICE=$(echo $LINE | cut -d ' ' -f 1)
	COUNT=1
	FS_LABEL=$(e2label $DEVICE)
	(e2fsck -p $DEVICE ; echo $? >/tmp/fsck-res) &
	echolcd -e "Checking filesystem: $FS_LABEL \\$COUNT"
	let COUNT++
	usleep 100000
	while [ ! -s /tmp/fsck-res ]
	do
		echolcd -e "Checking filesystem: $FS_LABEL \\$COUNT"
		let COUNT++
		if [ $COUNT -gt 8 ]; then
			COUNT=1
		fi
		usleep 100000
	done
	if [ $(cat /tmp/fsck-res) -gt 1 ]; then
		echolcd "Filesystem $FS_LABEL not ok"
		touch /tmp/reboot
		sleep 5
	fi
	rm -f /tmp/fsck-res
done

if [ -f /tmp/reboot ]; then
	/usr/bin/tail -fs 1 /dev/keyboard > /tmp/keypress &
	COUNT=10
	while [ $COUNT -ge 0 ]
	do
		echolcd "Rebooting to recheck filesystems  (press '1' to abort $COUNT)"
		KEY=$(cat /tmp/keypress | cut -c 1)
		if [ "$KEY" = "1" -o "$KEY" = "%" ]; then
			/usr/bin/killall tail
			rm -f /tmp/reboot
			rm -f /tmp/keypress
			if [ "$KEY" = "%" ]; then
				echolcd "Console started"
				exec /sbin/getty -n 57600 /dev/ttyAM0 -l /bin/sh
			fi
			break;
		fi

		# Empty out the keypress file?
		if [ -n "$KEY" ]; then
			/usr/bin/killall tail
			rm -f /tmp/keypress
			/usr/bin/tail -fs 1 /dev/keyboard > /tmp/keypress &
		fi
		sleep 1
		let COUNT--
	done
	if [ -f /tmp/reboot ]; then
		echolcd "Rebooting..."
		/sbin/reboot
		sleep 100
	fi
else
	echolcd "All filesystems OK"
fi

# Remount root filesystem rw, so other RC scripts will run correctly
/bin/mount -o remount,rw /

# Umount /tmp, because other RC files will mount it
/usr/bin/umount /tmp

