#!/bin/sh -e
#
# Test if the timezone is correct.

if test -r /etc/debian-edu/config ; then
    . /etc/debian-edu/config
fi

if [ ! -f /etc/localtime ] ; then
    echo "error: $0: The file /etc/localtime is missing."
    exit
fi

if [ -z "$(cat /etc/timezone)" ] ; then
    echo "warning: No value in /etc/timezone."
fi

# Find the matching zonefile(s)
id=$(md5sum /etc/localtime | awk '{print $1}')
curzones=$(cd /usr/share/zoneinfo; find . -type f |xargs md5sum | grep $id |awk '{print $2}' | sed 's/\.\///')

map_locale_to_timezone() {
    case "$1" in
	*_BE*)
	    localzone="Europe/Brussels"
	    ;;
	*_BR*)
	    localzone="America/Sao_Paulo America/Noronha \
	               America/Belem America/Fortaleza \
		       America/Recife America/Araguaina \
		       America/Maceio America/Cuiaba \
		       America/Porto_Velho America/Boa_Vista \
		       America/Manaus America/Eirunepe \
		       America/Rio_Brancor"
	    ;;
	*_DE*)
	    localzone="Europe/Berlin"
	    ;;
	*_DK*)
	    localzone="Europe/Copenhagen"
	    ;;
	*_ES*)
	    localzone="Europe/Madrid"
	    ;;
	*_FI*)
	    localzone="Europe/Helsinki"
	    ;;
	*_FR*)
	    localzone="Europe/Paris"
	    ;;
	*_IT*)
	    localzone="Europe/Rome"
	    ;;
	*_LV*)
	    localzone="Europe/Riga"
	    ;;
	*_MX*)
	    localzone="America/Mexico_City America/Cancun America/Merida \
	               America/Monterrey America/Mazatlan America/Chihuahua \
		       America/Hermosillo America/Tijuana"
	    ;;
	*_NL*)
	    localzone="Europe/Amsterdam"
	    ;;
	*_NO*)
	    localzone="Europe/Oslo"
	    ;;
	*_PL*)
	    localzone="Europe/Warsaw"
	    ;;
	*_SE*)
	    localzone="Europe/Stockholm"
	    ;;
	*)
	    # Accept the existing value if the default language is unspecified
	    localzone="unknown";
	    ;;
    esac
    # Convert newlines to spaces
    localzone="$(echo $localzone)";    
}

map_locale_to_timezone "$LOCALE"

foundZone=
for zone in $localzone; do
    for curzone in $curzones ; do
	if test "$curzone" = "$zone"; then
	    foundZone=$curzone
	fi
    done
done

if [ "$foundZone" ] ; then
    echo "success: $0: Time zone is '$foundZone'."
else
    if [ unknown = "$localzone" ] ; then
	echo "warning: Correct time zone for locale '$LOCALE' is not known."
    else
	echo "error: $0: /etc/localtime is not equal to ($localzone)."
    fi
fi
