#!/bin/sh
# tzchange.sh
#	update system timezone files after travelling
#
#	usage: tzchange City|Region/City

zoneinfo=/usr/share/zoneinfo
etcloc=/etc/localtime
etctz=/etc/timezone

VFLAG=
if [ "$1" = "-v" ]; then
	VFLAG=1
	shift
fi

if [ $# -ne 1 ]; then
	echo usage: tzchange City\|Region/City 1>&2
	exit 1
fi

# get tz name
tz=$1

# expand tz name to Region/City
case "$tz" in
*/*)	;;
*)	tzs=`find $zoneinfo -type f -name "*$tz*" | sed "s,^$zoneinfo/,," | tr "\n" " " | sed 's, $,,'`
	case "$tzs" in
	"")	echo "tzchange: zone $tz not found" 1>&2
		exit 1
		;;
	*" "*)	echo "tzchange: zone $tz matches multiple zones, please specify one" 1>&2
		echo tzchange: $tzs 1>&2
		exit 1
		;;
	*)	tz=$tzs	
		;;
	esac
	;;
esac

# check tz exists
if [ ! -f "$zoneinfo/$tz" ]; then
	echo "tzchange: zone $tz does not exist" 1>&2
	exit 1
fi

# set tz as local time info
[ -n "$VFLAG" ] && echo cp -p $zoneinfo/$tz $etcloc
cp -p $zoneinfo/$tz $etcloc

# clear any previous zone name override
[ -n "$VFLAG" ] && echo rm -f $etctz
rm -f $etctz

# get tzname() value for this zone
# nb: if zoneinfo file is defined in tzdata as a "Link" to another zoneinfo file
#     tzname() may return the other zone's name
tddt=`perl -e 'use TDcal::timezone; printf "%s\n", tzname();'`

# if zone name not the desired one, override it in timezone file
if [ "$tddt" != "$tz" ]; then
	[ -n "$VFLAG" ] && echo tddt=$tddt tz=$tz
	[ -n "$VFLAG" ] && echo echo $tz \>$etctz
	echo $tz >$etctz
fi

exit 0
