#!/bin/sh -e
# initramfs local-premount script for fixrtc

PREREQ=""

# Output pre-requisites
prereqs()
{
        echo "$PREREQ"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

# use the fixrtc cmdline option in your bootloader to
# automatically set the hardware clock to the date of
# the last mount of your root filesystem to avoid fsck
# to get confused by the superblock being in the future

BROKEN_CLOCK=""
ROOTDEV=""

for x in $(cat /proc/cmdline); do
        case ${x} in
        root=*)
                value=${x#*=}

                # Find the device node path depending on the form of root= :

                case ${value} in
                UUID=*)
                        ROOTDEV=/dev/disk/by-uuid/${value#UUID=}
                        ;;
                LABEL=*)
                        ROOTDEV=/dev/disk/by-label/${value#LABEL=}
                        ;;
                *)
                        ROOTDEV=${value}
                        ;;
                esac
        ;;
        fixrtc)
                BROKEN_CLOCK=1
        ;;
        esac
done

if [ -n "$BROKEN_CLOCK" -a -n "$ROOTDEV" ];then
        ROOTDISK=$(readlink -f "$ROOTDEV")

        TIMESTR=$(dumpe2fs -h "$ROOTDISK" 2>/dev/null|grep "Last mount time")
        TIME=${TIMESTR#*:}

	hwclock -s

	MOUNTTIME=$(date --utc --date  "${TIME}"  +%s)
	CURDATE=$(date --utc --date "$(date)" +%s)

	if [ "$MOUNTTIME" -gt "$CURDATE" ]; then
        	date --set="${TIME} 1 minute" >/dev/null 2>&1
	fi
fi

# This script is best-effort.  If we couldn't fudge the clock as desired,
# just try to carry on boot anyway:
# It will probably fail, but we won't have made the situation any worse.
exit 0
