#! /bin/bash

# cron reads timezone information at startup only
# this programs restarts cron if timezone has changed

set -e

VERSION='0.3'
test -x "/etc/init.d/cron" || exit 0

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'
if [ -r "$CONFFILE" ]; then
    . $CONFFILE
fi

# sorry for my dumb command line argument parser :-)
case "$1" in
    --test)
	VERBOSE='2'
	;;
    --version)
	echo "tz-brasil-restart-cron version $VERSION"
	echo '(c) 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-restart-cron [ --test | --version | --help ]'
	echo '  --help    : print this screen and exit'
	echo '  --version : print program version and exit'
	echo '  --test    : run in verbose mode'
	exit 0
	;;
    '')
        # no cmdline arguments
	;;
    *)
	echo "Unknown command line argument: '$1'" >&2
	echo 'Try: tz-brasil-restart-cron --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 [ ! -e "$LASTTZFILE" ]; then
    echo "Unknown" > /var/lib/tz-brasil/last-timezone
fi

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

echo "*** tz-brasil-restart-cron ***" >&2
echo "timezone has changed from '$LASTTZ' to '$CURRTZ'; need to restart cron" >&2
/etc/init.d/cron restart >&2
echo "$CURRTZ" > $LASTTZFILE
exit 0
