#!/bin/sh

# A small script used to set the time under Linux with hwclock...

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

# Function used to abort the script.
function abort() {
	Xdialog --title "$TITLE" --msgbox "Aborted." 0 0
	exit 0
}


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

# Search for adjtime IOT to know if the RTC was last set in UTC.
# If adjtime is not found then look at the /etc/sysconfig/clock
# file and in last ressort, if nothing can be deduced automatically,
# then ask the user...
if [ -f /etc/adjtime ] ; then
	UTC=`grep UTC /etc/adjtime`
	if [ "$UTC" == "UTC" ] ; then
		UTC="--utc"
	fi
else
	if [ -f /etc/sysconfig/clock ] ; then
		. /etc/sysconfig/clock
		if [ "$UTC" == "no" ] || [ "$UTC" == "false" ] ; then
			UTC=""
		else
			UTC="--utc"
		fi
	else
		Xdialog --title "$TITLE" --yesno "Is the RTC set in UTC ?" 0 0
		case $? in
			0)
				UTC="--utc" ;;
			1)
				UTC="" ;;
			255)
				abort ;;
		esac
	fi
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
	abort
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
	abort
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 $UTC --date "$NEWDATE $NEWTIME" 2>>/tmp/set-time.err.$$
if (( $? == 0 )) ; then
	/sbin/hwclock --hctosys $UTC 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.$$
