#!/bin/bash

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

if [ ! -r "$CONFFILE" ]; then
  echo "could not read configuration file: $CONFFILE"
  exit 1
fi

. $CONFFILE

if [ "`cat /etc/timezone`" != "$TIME_ZONE" ]; then
  echo "Current timezone is `cat /etc/timezone`"
  echo "Please change it to $TIME_ZONE"
  echo "Use the command 'tzconfig' to do it"
  exit 77
fi

if [ "$1" == "test" ]; then
  VERBOSE=2
fi
if [ "$1" == "force" ]; then
  VERBOSE=2
  rm -f $VARDIR/$STAMPFILE
fi

case $VERBOSE in
  0)
    DEBUG='/dev/null'
    DEBUGERR='/dev/null'
    ;;
  1)
    DEBUG='/dev/null'
    DEBUGERR='/dev/stderr'
    ;;
  *)
    DEBUG='/dev/stderr'
    DEBUGERR='/dev/stderr'
    ;;
esac

find $VARDIR -mtime -4 2>/dev/null | grep $STAMPFILE >/dev/null
if [ "$?" == "0" ]; then
  # there was an successfull update newer than one week
  # we will only try an update if last update is older than 4 days
  echo "there was an successfull update in the last 4 days." > $DEBUG
  echo "will not try to update again" > $DEBUG
  echo "remove the file '$VARDIR/$STAMPFILE' if you want to update now" > $DEBUG
  echo "Exit code 0" > $DEBUG
  exit 0
fi

echo "generating a new tempfile" > $DEBUG
TMP=`tempfile 2> $DEBUGERR`
echo "tempfile is $TMP" > $DEBUG
echo "Command: wget $WGETOPTS $SERVER$FILE -O $TMP" > $DEBUG
wget $WGETOPTS "$SERVER$FILE" -O "$TMP" > $DEBUG 2> $DEBUG
if [ "$?" != "0" ]; then
  # failed to get file
  echo "Failed to get file from server" > $DEBUGERR
  rm -f $TMP > $DEBUGERR 2>&1
  echo "Exit code 2" > $DEBUGERR
  exit 2
fi

echo "Got the file, now lets see it..." > $DEBUG

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

diff $ZIC $TMP >/dev/null 2>&1
if [ "$?" == "0" ]; then
  echo "The retrieved file is the same" > $DEBUG
  rm -f $TMP > $DEBUGERR 2>&1
  touch $VARDIR/$STAMPFILE > $DEBUG 2> $DEBUGERR
  if [ "$?" != "0" ]; then
    echo "Could not touch timestamp"
    exit 5
  fi
  echo "Success" > $DEBUG
  echo "Exit code 0" > $DEBUG
  exit 0
fi

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

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

cat $TMP > $ZIC
rm -fv $TMP > $DEBUG 2> $DEBUGERR
touch $VARDIR/$STAMPFILE > $DEBUG 2> $DEBUGERR
if [ "$?" != "0" ]; then
  echo "Could not touch timestamp"
  exit 5
fi
echo "Success" > $DEBUG
exit 0
