#!/bin/bash
#
# Utility to assist in setting up cron jobs that run in another timezone (such
# as one with DST).
#
# Set up the cron as: cron_tz.sh "Europe/London" 07 /your/cmd
# which runs /your/cmd at 7am in the timezone Europe/London (minute offsets in
# the cron will be preserved).  Command is optional, if not supplied, it'll
# only sleep and then exit.
#
# The script checks if the hour ("07") has been reached yet the specified TZ and
# sleeps until that time if not.

if [ $# -lt 2 ]
then
    echo "Usage: $0 TIMEZONE TZHOUR [COMMAND...]" >&2
    exit 1
fi

TZHOUR=$2
HOURNOW=$(TZ="$1" date +%k)

[ $TZHOUR -lt $HOURNOW ] && TZHOUR=$(($TZHOUR + 24))
HOURWAIT=$(($TZHOUR - $HOURNOW))
sleep $(($HOURWAIT * 3600))

# Exit or run a given command if supplied
[ $# -eq 2 ] && exit 0
shift 2
exec "$@"
