#! /bin/bash

# some programs (cron, syslog) read timezone information at startup only
# this programs restarts them if timezone has changed

set -e

VERSION='0.8'

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'
VERBOSE='1'
FORCE='0'
RUN_PROG=''
if [ -r "$CONFFILE" ]; then
    . $CONFFILE
fi

# sorry for my dumb command line argument parser :-)
case "$1" in
    --test|--verbose)
	VERBOSE='2'
	;;
    --force)
        VERBOSE='2'
	FORCE='1'
	;;
    --version)
	echo "tz-brasil-restart version $VERSION"
	echo '(c) 2004-2006 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-restart [ --verbose | --force | --version | --help ]'
	echo '  --help    : print this screen and exit'
	echo '  --version : print program version and exit'
	echo '  --verbose : run in verbose mode'
	echo '  --force   : force restart of programs, run in verbose mode'
	exit 0
	;;
    '')
        # no cmdline arguments
	;;
    *)
	echo "Unknown command line argument: '$1'" >&2
	echo 'Try: tz-brasil-restart --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

LASTTZFILE='/var/lib/tz-brasil/last-timezone'
CURRTZ=`/bin/date '+%z/%Z'`

umask 022

if [ "$FORCE" == "1" ]; then
    echo "--force: programs will be restarted"
    echo "Unknown" > $LASTTZFILE
fi
if [ ! -e "$LASTTZFILE" ]; then
    echo "$CURRTZ" > $LASTTZFILE
fi

LASTTZ=`cat $LASTTZFILE`
if [ "$CURRTZ" == "$LASTTZ" ]; then
    # timezone did not change
    echo "*** tz-brasil-restart ***"
    echo "current and last timezone are the same '$LASTTZ'. no need to restart"
    exit 0
fi

echo "*** tz-brasil-restart ***" >&2
echo "timezone has changed from '$LASTTZ' to '$CURRTZ'; need to restart" >&2
set +e
if [ -x "/etc/init.d/sysklogd" ]; then
  /etc/init.d/sysklogd restart >&2
  echo "--- sysklogd restart exit status = $?"
fi
if [ -x "/etc/init.d/cron" ]; then
  /etc/init.d/cron restart >&2
  echo "--- cron restart exit status = $?"
fi
test ! -x /etc/init.d/sysklogd || /etc/init.d/sysklogd restart >&2
if [ "$RUN_PROG" != "" ]; then
    echo "--- begin of exec '$RUN_PROG' ---" >&2
    $RUN_PROG "$LASTTZ" "$CURRTZ" >&2
    echo "--- end of exec --- exit status = $? ---" >&2
fi
set -e
echo "$CURRTZ" > $LASTTZFILE
exit 0
