#!/bin/sh

# Title to be used for all Xdialog boxes.
TITLE="Set time tool"

# Now check for hwclock existence...
if ! [ -f /sbin/hwclock ] ; then
	Xdialog --title "$TITLE" --msgbox "/sbin/hwclock not found..." 0 0
	exit 0
fi

# Get the date (returned in DD/MM/YYYY format by Xdialog.
ENTEREDDATE=`Xdialog --stdout --title "$TITLE" --calendar "Please set the date..." 0 0 0 0 0`

if (( $? != 0 )) ; then
	Xdialog --title "$TITLE" --msgbox "Aborted." 0 0
	exit 0
fi

# Convert the date to the MM/DD/YYYY format needed by hwclock.
NEWDATE=`echo "$ENTEREDDATE" | awk --source 'BEGIN { FS="/" }' --source '{ print $2 "/" $1 "/" $3 }'`

# Get the time in HH:MM:SS format.
NEWTIME=`Xdialog --stdout --title "$TITLE" --timebox "Please set the time..." 0 0`

if (( $? != 0 )) ; then
	Xdialog --title "$TITLE" --msgbox "Aborted." 0 0
	exit 0;
fi

# Prepare the error log file.
echo "Error while trying to set the system clock !" >/tmp/set-time.err.$$
echo "Reason:" >>/tmp/set-time.err.$$
echo "" >>/tmp/set-time.err.$$

# Set the hardware clock (RTC) and then the system clock, appending any error
# message to the error log...
/sbin/hwclock --set --date "$NEWDATE $NEWTIME" 2>>/tmp/set-time.err.$$
if (( $? == 0 )) ; then
	/sbin/hwclock --hctosys 2>>/tmp/set-time.err.$$
fi

# Give the result (success or failure+reason)...
if (( $? == 0 )) ; then
	Xdialog --title "$TITLE" --msgbox "The system clock has been set." 0 0
else
	Xdialog --title "$TITLE" --textbox /tmp/set-time.err.$$ 60 30
fi

rm -f /tmp/set-time.err.$$
