#!/bin/sh

clear
echo "                       TIME ZONE CONFIGURATION (timezone)"
echo "                       =================================="
echo

# This ought to be /etc/zoneinfo so we can have a seperate filesystem
# mounted on /usr. Unfortunately this is hard coded in the shared libc.
ZIFDIR=/usr/lib/zoneinfo

# Preserve existing localtime and posixrules and restore them on exit.
trap "cd $ZIFDIR; mv -f .localtime localtime 2>/dev/null; mv -f .posixrules posixrules 2>/dev/null" \
	0
(cd $ZIFDIR; mv -f localtime .localtime 2>/dev/null; mv -f posixrules .posixrules 2>/dev/null)

cd $ZIFDIR

# Recover from being bounced by symlinks...
ZIFDIR=`pwd`

echo
echo "Available time zones:"
echo
ls -C
echo

zone=
while [ ! -f "$zone" -a "$zone" != "quit" ]
do
	echo -n "Enter time zone (blank for list): "
	read zone
	if [ -z "$zone" ]; then
		echo
		echo "Available time zones:"
		echo
		ls -C
		echo
	elif [ -d "$zone" ]; then
		case "$zone" in
			/*)
				echo
				echo "Absolute path names aren't allowed!"
				echo
				zone=
				;;
			..*|./..*)
				if [ "`pwd`" = $ZIFDIR ]; then
					echo
					echo "Already in the top directory"
					echo
					zone=
				else
					cd $zone
					echo
					echo "Available time zones:"
					echo
					ls -C
					echo
				fi
				;;
			*)
				cd $zone
				echo
				echo "Time zone $zone contains the following sub-zones"
				echo
				ls -C
				echo
				;;
		esac
	elif [ ! -f "$zone" -a "$zone" != "quit" ]; then
		echo
		echo "Invalid time zone: $zone"
		echo
	fi
	
done

if [ "$zone" != "quit" ]; then
	# We always use US/Central for the posixrules here. If you
	# have good reason to want something else here you probably
	# understand this better than I do and can do it by hand.
	# Posixrules defines how the TZ environment variable is to
	# be interpreted. For strict POSIX behaviour it should be
	# a US zone. See the documentation.
	#
	# Note that we install these as dot files. We have a trap set
	# that cleans the zoneinfo directory and renames the dot files
	# appropriately when we exit.
	ln -f $ZIFDIR/US/Central $ZIFDIR/.posixrules
	ln -f `pwd`/$zone $ZIFDIR/.localtime

	echo
	echo "Time zone on this machine is set to $zone"
	echo

	ans=
	while [ "$ans" != "y" -a "$ans" != "Y" -a "$ans" != "n" -a "$ans" != "N" ]
	do
		echo -n "Is your hardware clock set to GMT/UCT? (y/n): "
		read ans
	done

	if [ "$ans" = "y" -o "$ans" = "Y" ]; then
		flag=GMT
	else
		flag=LOCAL
	fi
	awk " \
		\$1 == \"HWCLOCK\" { print \"HWCLOCK	$flag\" } \
		\$1 != \"HWCLOCK\" { print \$0 } \
	" /etc/default/clock > /etc/default/,clock
	rm -f /etc/default/clock
	mv /etc/default/,clock /etc/default/clock
fi
