#!/bin/sh

set -e

if [ "x$1" = "xconfigure" ]; then

    trap "echo ; \
	echo Received signal... exiting. ; \
	echo ; \
	echo To set your time zone at a later date, use dpkg --configure. ; \
	exit 1" 1 2 3 15

    if [ -f /var/lib/dpkg/info/timezone.postrm ]; then
	rm /var/lib/dpkg/info/timezone.postrm
	echo '#! /bin/sh' >>/var/lib/dpkg/info/timezone.postrm
	echo 'set -e' >>/var/lib/dpkg/info/timezone.postrm
	chmod +x /var/lib/dpkg/info/timezone.postrm
    fi

    if [ -f /etc/timezone ]; then
	timezone=`cat /etc/timezone`
	if [ "$timezone" = "Factory" ]; then 
	    rm /etc/timezone
	fi
    fi

    if [ ! -f /etc/timezone ] ; then
	    echo "You don't have a default time zone or a"
	    echo "/etc/timezone file associated with your"
	    echo "currently set timezone."
	    echo "Running /usr/sbin/tzconfig..."
	    /usr/sbin/tzconfig
    fi

    timezone=`cat /etc/timezone`
    if [ -f /usr/share/zoneinfo/$timezone ]; then
	echo "Your default time zone is $timezone."
	echo "Run /usr/sbin/tzconfig to change it"
    else
	echo "Hmm... /etc/timezone contains an invalid timezone."
	echo -n "Checking if it's US/Pacific-New..."
	if [ "$timezone" = "US/Pacific-New" ]; then
	    echo "yes."
	    echo "Transforming US/Pacific-New to US/Pacific."
	    timezone=US/Pacific
	    rm /etc/timezone
	    echo "US/Pacific" > /etc/timezone
	else
	    echo "no."
	    rm /etc/timezone
	    echo "Running /usr/sbin/tzconfig to fix it..."
	    /usr/sbin/tzconfig
	fi
    fi
    if [ ! -L /etc/localtime ]; then
	rm -f /etc/localtime
	if [ -f /usr/share/zoneinfo/$timezone ]; then
	    ln -sf /usr/share/zoneinfo/$timezone /etc/localtime
	else
	    echo "Timezone is still invalid, this shouldn't happen."
	    exit 1
	fi
    fi
    ln -sf /etc/localtime /usr/share/zoneinfo/localtime
fi

exit 0
