#!/bin/sh

. /usr/share/alterator/build/backend3.sh

ZONEINFODIR=/usr/share/zoneinfo

ZONETABFILE=/usr/share/zoneinfo/zone.tab
ISOTABFILE=/usr/share/zoneinfo/iso3166.tab


LOCAL_ZONETABFILE=/etc/sysconfig/alterator/timezone/zone.tab
LOCAL_ISOTABFILE=/etc/sysconfig/alterator/timezone/iso3166.tab

SYSCONFIG_CLOCK=/etc/sysconfig/clock

DATADIR=/usr/share/alterator-tzone/


_()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-tzone" "$1"
}

__()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-tzone-tz" "$1"
}

is_yes()
{
	case "$1" in
		yes|Yes|YES|true|True|TRUE|on|On|ON|Y|y|1) return 0 ;;
		*) return 1 ;;
	esac
}



error()
{
	printf '(error "%s")' "$*"
}


add_or_subst()
{
	if grep -qs "^[[:space:]]*$1=" "$SYSCONFIG_CLOCK"; then
		sed -i -e "s#^[[:space:]]*$1=.*#$1=\"$2\"#g" "$SYSCONFIG_CLOCK"
	else
		printf 'ZONE="%s"' "$2" >> "$SYSCONFIG_CLOCK"
	fi
}

cat_isotabfile()
{
    local SEP='	'
    local IFS="$SEP"
    local TR_ISOTABFILE="$DATADIR/iso3166.tab.${in_language%%;*}"
    
    grep -v '^[[:space:]]*#' "$ISOTABFILE"|
	if [ -s "$TR_ISOTABFILE" ];then
	    join -j1 -o 2.1,1.2,2.2 -t"$SEP" -a2  "$TR_ISOTABFILE" -  |
		while read code trans eng;do
		    printf '%s\t%s\n' "$code" "${trans:-$eng}"
		done
	else
    	    cat
	fi|
	LANG=${in_language%%;*}.utf8 sort -k2,2
}

read_zone() {
	local ZONE= country= country_code=

	local language="$INSTALLER_LANGUAGE"
	[ -n "$language" ] || language="${in_language%%;*}"

	. /etc/sysconfig/clock

	if [ -z "$ZONE" ]; then
		local region="$(printf %s "$language" |
				sed -r -e 's,[a-z]+_([^\.]+)(\..*)?,\1,' |
				tr '[:lower:]' '[:upper:]')"

		[ -z "$region" ] ||
			ZONE="$(grep "^$region[[:space:]]" "$DATADIR/defaultzones" |cut -f2)"

		[ -n "$ZONE" ] ||
			ZONE="Europe/London"
	fi
	
	printf %s\\n "$ZONE"
}

list_zones() {
	local IFS="	"
	local country_code= code coordinates zone comments
				
	country_code="${in__objects%/*}"
				
	grep "^$country_code[[:space:]]" "$ZONETABFILE" |
	while read code coordinates zone comments; do
		tr_zone="`__ "$zone"`"
		printf '("%s" label "%s")\n' "$zone" "${tr_zone#*/}"
	done
}

read_utc()
{
    local UTC= val=
    . "$SYSCONFIG_CLOCK"
    is_yes "$UTC" && echo "#t" || echo "#f"
}

write_utc()
{
	if grep -qs "^[[:space:]]*UTC=" "$SYSCONFIG_CLOCK"; then
		sed -i -e "s#^[[:space:]]*UTC=.*#UTC=\"$1\"#g" "$SYSCONFIG_CLOCK"
	else
		cat > "$SYSCONFIG_CLOCK" <<-EOF
		# UTC=true indicates that the clock is set to UTC; 
		# anything else indicates that it is set to local time.
		UTC="$1"
		EOF
	fi
}

[ ! -s "$LOCAL_ZONETABFILE" ] || ZONETABFILE="$LOCAL_ZONETABFILE"
[ ! -s "$LOCAL_ISOTABFILE" ] || ISOTABFILE="$LOCAL_ISOTABFILE"

contry_code=
on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			printf 'name (label "%s")' "`_ "Country"`"
			printf 'zone (label "%s")' "`_ "Time zone"`"
			printf 'utc  (label "%s")' "`_ "Hardware time set to GMT"`"
			echo ')'
			;;
		list)
			echo '('
			if [ "$in__objects" = "/" ]; then
				cat_isotabfile|
				    sed -r -e 's,([^[:space:]]+)[[:space:]]+(.*),("\1" label "\2"),'
			elif [ "${in__objects##*/}" = "zones" ]; then
				list_zones
			fi
			echo ')'
			;;
	    	read)
			echo '('
			if [ "$in__objects" == "/" ];then
				# read current zone info (country)

				local zone= country_code=
				zone="$(read_zone)"

				country_code="$(cut -f1,3 "$ZONETABFILE" |grep "[[:space:]]$zone" |cut -f1)"

				printf 'name "%s"\n' "$country_code"
			        printf 'utc %s\n' "$(read_utc)"

			else
				# read zone info for selected contry (default town?)
				local zone=
				
				zone="$(read_zone)"
				printf 'zone "%s"\n'  "$zone"
			fi
			echo ')'
			;;
		write)
			[ "$in_utc" = "#t" ] && write_utc "true" || write_utc "false"

			if [ -n "$in_zone" ]; then
				if [ ! -f "$ZONEINFODIR/$in_zone" ]; then
					error "Timezone file not found"
					return
				fi
				add_or_subst "ZONE" "$in_zone"
				cp -f -- "$ZONEINFODIR/$in_zone" /etc/localtime

			fi
			if [ "$in_installer" = "#t" ];then
			    service clock start >/dev/null 2>/dev/null
			else
			    service clock sync >/dev/null 2>/dev/null
			fi
			echo '()'
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
