#!/bin/bash
# console-config/src/sbin-scripts/tz-setup
# 
#  Copyright: ©2013, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
# Timezone setup script. Presents user with menu allowing selection of
# timezone, and then modifies the /etc/timezone/localtime.local symlink
# to enact the change.
#

echo "Building list of timezones..."

declare -a MENU

# list each file in alphabetically; most but not all are in subdirectories
for X in /usr/share/zoneinfo/*
do
	if [ -d "${X}" ]
	then
		for Y in ${X}/*
		do
			MENU+=("${Y:20:999}")
			MENU+=("")
		done
	else
		MENU+=("${X:20:999}")
		MENU+=("")
	fi
done

# maybe specify a default, but don't pass invalid arguments to dialog if there
# is a corrupt symlink
TZ="`readlink -f /etc/localtime`"
if [ "${TZ:0:20}" = "/usr/share/zoneinfo/" -a -s "${TZ}" ]
then
	MENU_DEFAULT="--default-item ${TZ:20:999}"
else
	MENU_DEFAULT="--default-item UTC"
fi

# create the dialog and save its result
DIALOG_RESULTFILE="`mktemp`"
trap "rm -f \"${DIALOG_RESULTFILE}\"" EXIT

dialog --title "Choose timezone" \
	${MENU_DEFAULT} \
	--menu "Select timezone for display. Note that this does not affect \
data timestamps, which are always processed in UTC: it simply causes the \
system to display any dates/times in the selected local timezone." \
	0 0 0 \
	"${MENU[@]}" \
	2> "${DIALOG_RESULTFILE}"
if [ $? -ne 0 ]
then
	clear
	echo "Cancelled."
	exit 1
fi

clear
TZ="`cat "${DIALOG_RESULTFILE}"`"
echo "Selected timezone: ${TZ}"

# create the symlink
ln -sf "/usr/share/zoneinfo/${TZ}" "/etc/timezone/localtime.local"
[ $? -eq 0 ] || exit 1

echo "Already-running programs and services will need to be restarted (or the"
echo "system rebooted) for the new timezone to take effect."
