#!/bin/sh
# Hardware Clock (RTC) TEST
#
#-------------
HWCLOCK=/sbin/hwclock
SETOLD_DATETIME=121212342002.00
SETCUR_DATETIME=010100002007.00
##SETCUR_CKDATES=`date -d ${SETCUR_DATETIME} +%s`  This code is Error
SETCUR_CKDATES=1167577200

DEBUG=
if [ -n $1  ];then
	DEBUG=$1
fi

test ${DEBUG} && echo "1:`date`"
#-------------
${HWCLOCK} --hctosys >/dev/null 2>&1
if [ $? -ne 0 ]; then
	echo "ERROR (read device error)"
	exit 1
fi

#-------------
CRDATES=`date +%s`
if [ x${DEBUG} != x  ];then
	echo "2:`date`"
	echo "SETCUR_CKDATES =${SETCUR_CKDATES}"
	echo "CRDATES =${CRDATES}"
fi

if [ ${CRDATES} -lt ${SETCUR_CKDATES} ] ; then
	date ${SETCUR_DATETIME} >/dev/null 
fi
test ${DEBUG} && echo "3:`date`"

${HWCLOCK} --systohc >/dev/null 2>&1
if [ $? -ne 0 ]; then
	echo "ERROR (write device error)"
	exit 2
fi
#-------------
CKDATES=`date +%s`

date ${SETOLD_DATETIME} >/dev/null 
sleep 1
CKDATES1=`expr ${CKDATES} + 2`

#-------------
test ${DEBUG} && echo "4:`date`"
${HWCLOCK} --hctosys >/dev/null 2>&1
if [ $? -ne 0 ]; then
	echo "ERROR (read device error)"
	exit 3
fi
CRDATES=`date +%s`
if [ x${DEBUG} != x  ];then
	echo "5:`date`"
	echo "CKDATES =${CKDATES}"
	echo "CKDATES1=${CKDATES1}"
	echo "CRDATES =${CRDATES}"
fi

#-------------
if [ ${CRDATES} -eq ${CKDATES1} ];then
	test ${DEBUG} && echo "OK (uptime)"
else
	echo "ERROR (no uptime)"
	exit 4
fi

echo "OK"
exit 0
