#!/bin/sh
#
# timezone	Set time zone information.
# chkconfig:	2345 10 90
# description:	This script is setting time zone information for your machine.
#

[ -f /etc/sysconfig/timezone ] || exit 0

# Source function library.
. /etc/rc.d/init.d/functions

. /etc/sysconfig/timezone

ZONE_FILE="$ZONE_INFO_DIR"

if [ -n "$ZONE_INFO_SCHEME" -a "$ZONE_INFO_SCHEME" != "posix" ]; then
	ZONE_FILE="$ZONE_FILE/$ZONE_INFO_SCHEME"
fi

ZONE_FILE="$ZONE_FILE/$TIMEZONE"

[ -L /etc/localtime ] && [ "$(resolvesymlink /etc/localtime)" = "$ZONE_FILE" ] && exit 0

start() {
	if [ -f /var/lock/subsys/timezone ]; then
		msg_already_running timezone
		return
	fi

	if [ -f "$ZONE_FILE" ]; then
		rm -f /etc/localtime

		MESSAGE=$(nls 'Setting time zone information (%s)' "$TIMEZONE")

		if [ -n "$(awk '$2 == "/usr" { print $2 }' /proc/mounts 2> /dev/null)" ]; then
			run_cmd "$MESSAGE" cp -af "$ZONE_FILE" /etc/localtime
		else
			run_cmd "$MESSAGE" ln -sf "$ZONE_FILE" /etc/localtime
		fi
		RETVAL=$?
		restorecon /etc/localtime >/dev/null 2>&1
	else
		show "Missing %s file" "$ZONE_FILE"
		fail
		RETVAL=2
	fi

	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/timezone
}

stop() {
	rm -f /var/lock/subsys/timezone >/dev/null 2>&1
}

disable() {
	run_cmd "Unsetting time zone information" rm -f /etc/localtime
}

# return true if FILE1 and FILE2 are identical
identical() {
	local crc1 crc2
	test -f "$1" || return 1
	test -f "$2" || return 1
	crc1=$(cksum "$1" | awk '{print $1}')
	crc2=$(cksum "$2" | awk '{print $1}')
	[ "$crc1" = "$crc2" ]
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|try-restart|reload|force-reload)
	stop
	start
	;;
  disable)
	disable
	;;
  status)
	nls 'Timezone is configured to %s' "$TIMEZONE"
	if [ ! -f "$ZONE_FILE" ]; then
		nls "Missing %s file" "$ZONE_FILE"
		exit 1
	elif ! identical "$ZONE_FILE" /etc/localtime; then
		nls 'Current time zone differs from %s' "$TIMEZONE"
		exit 1
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|reload|force-reload|disable|status}"
	exit 3
esac

exit $RETVAL
