#!/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

timezone="$(cat /etc/timezone)"

if [ -z "$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/\.\///' | sort)

map_locale_to_timezone() {
    case "$1" in
	*_BE*)
	    localzone="posix/Europe/Brussels"
	    ;;
	*_BR*)
	    localzone="posix/America/Sao_Paulo posix/America/Noronha \
	               posix/America/Belem posix/America/Fortaleza \
		       posix/America/Recife posix/America/Araguaina \
		       posix/America/Maceio posix/America/Cuiaba \
		       posix/America/Porto_Velho posix/America/Boa_Vista \
		       posix/America/Manaus posix/America/Eirunepe"
	    ;;
	*_DE*)
	    localzone="posix/Europe/Berlin Europe/Berlin"
	    ;;
	*_DK*)
	    localzone="posix/Europe/Copenhagen"
	    ;;
	*_ES*)
	    localzone="posix/Europe/Madrid"
	    ;;
	*_FI*)
	    localzone="posix/Europe/Helsinki"
	    ;;
	*_FR*)
	    localzone="posix/Europe/Paris"
	    ;;
	*_IT*)
	    localzone="posix/Europe/Rome"
	    ;;
	*_LV*)
	    localzone="posix/Europe/Riga"
	    ;;
	*_MX*)
	    localzone="Mexico/General posix/America/Cancun posix/America/Merida \
	               posix/America/Monterrey Mexico/BajaSur posix/America/Chihuahua \
		       posix/America/Hermosillo Mexico/BajaNorte"
	    ;;
	*_NL*)
	    localzone="posix/Europe/Amsterdam"
	    ;;
	*_NO*)
	    localzone="Europe/Oslo posix/Atlantic/Jan_Mayen Arctic/Longyearbyen"
	    ;;
	*_PL*)
	    localzone="posix/Europe/Warsaw"
	    ;;
	*_SE*)
	    localzone="posix/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 for $LOCALE is not equal to ($localzone), /etc/timezone is '$timezone'."
    fi
fi
