#! /bin/bash

VERSION='0.3'

if [ -z "$PATH" ]; then
    PATH='/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin'
else
    PATH="$PATH:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin"
fi

CONFFILE='/etc/tz-brasil.conf'
VARDIR='/var/lib/tz-brasil'
STAMPFILE='success-stamp'
RETRYFILE='failure-stamp'
ZIC='/var/lib/tz-brasil/info'

# this is the default configuration
VERBOSE='1'
SERVER='http://people.debian.org/~pzn/tz-brasil/'
FILE='tz-brasil.zic'
ALLOWED_TIME_ZONES='Noronha Belem Fortaleza Recife Araguaina Maceio Bahia Sao_Paulo Campo_Grande Cuiaba Porto_Velho Boa_Vista Manaus Eirunepe Rio_Branco'
WGETOPTS=''
FETCH_INTERVAL='15000'      # aprox 4 days
WARN_FETCH_INTERVAL='25000' # aprox 7 days
RETRY_INTERVAL='250'        # aprox 4 hours
ASSUME_PING_OK='false'

# read the config file
if [ ! -r "$CONFFILE" ]; then
    echo "could not read configuration file: $CONFFILE" >&2
    exit 32
fi
. $CONFFILE

# check if timezone is one of the allowed time zones
FOUND_TZ=""
CURR_TZ=`cat /etc/timezone`
for i in $ALLOWED_TIME_ZONES; do
    if [ "$CURR_TZ" == "America/$i" ]; then
	FOUND_TZ='1'
    fi
done
if [ -z "$FOUND_TZ" ]; then
    echo "Current timezone is '$CURR_TZ'"  >&2
    echo "Please change it to one of the allowed time zones" >&2
    echo -n "Allowed timezones are:" >&2
    for i in $ALLOWED_TIME_ZONES; do
	echo -n " America/$i" >&2
    done
    echo "" >&2
    echo "Use the command 'tzconfig' to do it" >&2
    exit 33
fi

# sorry for my dumb command line argument parser :-)
case "$1" in
    --info)
	echo -n "last successfull database retrieve: "
	if [ ! -e "$VARDIR/$STAMPFILE" ]; then
	    echo "unknown"
	else
	    cat "$VARDIR/$STAMPFILE"
	fi
	if [ -e "$VARDIR/$RETRYFILE" ]; then
	    echo -n "last fetch try: "
	    cat "$VARDIR/$RETRYFILE"
	fi
	exit 0
	;;
    --test)
	echo 'verbose mode set to 2'
	VERBOSE='2'
	;;
    --force)
	echo 'verbose mode set to 2'
	VERBOSE='2'
	echo 'removing old timestamp. forcing a new fetch'
	rm -fv $VARDIR/$STAMPFILE || exit 34
	rm -fv $VARDIR/$RETRYFILE || exit 34
	;;
    --version)
	echo "tz-brasil version $VERSION"
	echo '(c) 2002-2004 Pedro Zorzenon Neto <pzn@debian.org>'
	echo 'For licence details read copyright file.'
	echo 'On Debian systems, it can be found at /usr/share/doc/tz-brasil/copyright.'
	exit 0
	;;
    --help)
	echo 'Usage: tz-brasil [ --help | --force | --test | --version | --info ]'
	echo '  --help    : print this screen and exit'
	echo '  --version : print program version and exit'
	echo '  --force   : run in verbose mode, and force a timezone fetch'
	echo '  --test    : run in verbose mode'
	echo '  --info    : show last successful timezone retrieve age'
	exit 0
	;;
    '')
        # no cmdline arguments
	;;
    *)
	echo "Unknown command line argument: '$1'" >&2
	echo 'Try: tz-brasil --help' >&2
	exit 35
	;;
esac

case $VERBOSE in
    0)
        # supress STDOUT and STDERR
	exec >/dev/null 2>/dev/null
	;;
    1)
        # supress STDOUT
	exec >/dev/null
	;;
    *)
	;;
esac

umask 022

find $VARDIR -mmin -$FETCH_INTERVAL | grep "$STAMPFILE" >/dev/null
if [ "$?" == "0" ]; then
    echo "there was a successfull update not older than $FETCH_INTERVAL minutes. will not try to update again."
    echo 'run with argument "--force" if you want to update now'
    exit 0
fi

find $VARDIR -mmin -$RETRY_INTERVAL | grep "$RETRYFILE" >/dev/null
if [ "$?" == "0" ]; then
    echo "there was a retry not older than $RETRY_INTERVAL minutes. will not try to update again."
    echo 'run with argument "--force" if you want to update now'
    exit 0
fi

echo "touching retry-timestamp"
/bin/date --rfc-822 > $VARDIR/$RETRYFILE
if [ "$?" != "0" ]; then
    echo "Could not touch retry-timestamp" >&2
    exit 5
fi

echo -n "testing Internet connection: "
if [ "$ASSUME_PING_OK" == 'true' ]; then
    echo "skipped. ASSUME_PING_OK is set."
else
    fping -q www.debian.org
    if [ "$?" != "0" ]; then
	echo "failed. will try again later."
	find $VARDIR -mmin -$WARN_FETCH_INTERVAL | grep "$STAMPFILE" >/dev/null
	if [ "$?" != "0" ]; then
	    echo "Internet connection failed." >&2
	    echo "*** WARNING *** tz-brasil last successful retrieve is too old..." >&2
	    echo "Please connect to internet and run \"tz-brasil\" as root" >&2
	    echo "also try \"tz-brasil --test\" or \"tz-brasil --force\"" >&2
	    echo "" >&2
	    echo "if you have a dial-up or pppoe connection, just connect and it will automatically retrieve timezone information" >&2
	fi
	exit 2
    fi
    echo "ok"
fi

echo "generating a new tempfile"
TMP=`tempfile`
echo "tempfile is $TMP"
echo "Command: wget $WGETOPTS $SERVER$FILE -O $TMP"
wget $WGETOPTS "$SERVER$FILE" -O "$TMP" 2>&1
if [ "$?" != "0" ]; then
    # failed to get file
    rm -f $TMP
    echo "Command: wget $WGETOPTS $SERVER$FILE -O $TMP"
    echo "Failed to get file from server"
    find $VARDIR -mmin -$WARN_FETCH_INTERVAL | grep "$STAMPFILE" >/dev/null
    if [ "$?" != "0" ]; then
	echo "Command: wget $WGETOPTS $SERVER$FILE -O $TMP" >&2
	echo "failed to get file from server." >&2
	echo "*** WARNING *** tz-brasil last successful retrieve is too old..." >&2
	echo "Please connect to internet and run \"tz-brasil\" as root" >&2
	echo "also try \"tz-brasil --test\" or \"tz-brasil --force\"" >&2
	echo "" >&2
	echo "if you have a dial-up or pppoe connection, just connect and it will automatically retrieve timezone information" >&2
    fi
    exit 2
fi

echo "Got the file, now lets see it..."

if [ ! -e $ZIC ]; then
    # will create an empty file the first time it runs
    touch $ZIC
    if [ "$?" != "0" ]; then
	echo "Could not create $ZIC" >&2
	rm -f $TMP
	exit 3
    fi
fi

diff $ZIC $TMP
if [ "$?" == "0" ]; then
    echo "The retrieved file is the same"
    rm -f $TMP
    rm -f $VARDIR/$RETRYFILE
    /bin/date --rfc-822 > $VARDIR/$STAMPFILE
    if [ "$?" != "0" ]; then
	echo "Could not touch timestamp" >&2
	exit 5
    fi
    echo "Success"
    exit 0
fi

# show the diferences to the user
echo "The following lines were changed in the timezone information:" >&2
diff -uw $ZIC $TMP | egrep '^[+-][^+#-]' >&2
echo "" >&2

/usr/sbin/zic $TMP
if [ "$?" != "0" ]; then
    # failed to compile file
    echo "Failed to compile the file" >&2
    rm -fv $TMP
    exit 4
fi

cat $TMP > $ZIC
rm -fv $TMP
rm -f $VARDIR/$RETRYFILE
/bin/date --rfc-822 > $VARDIR/$STAMPFILE
if [ "$?" != "0" ]; then
    echo "Could not touch success-timestamp" >&2
    exit 5
fi
echo "Success"
exit 0
