#!/bin/bash

# patch-jaguartz.sh
# ==================
# Ian Ward Comfort, 2 February 2007
#
# This script attempts to patch a machine running version 10.2 of OS X or OS X
# Server to use updated timezone information from the Olson database hosted at
# ftp://elsie.nci.nih.gov. It uses zic(8) to compile new zoneinfo files (for
# POSIX-like applications).
#
# NOTE: Although Darwin's zic(8) is capable of incorporating leap second data
# into its zone files, this script does not take advantage of this capability.
# The stock zoneinfo directory appears to omit this information, so for maximal
# compatibility we do the same.
#
# Thanks to Jim Kirkum for contributing testing.

OLSON=2007a
PATH="/bin:/sbin:/usr/bin:/usr/sbin"

die () { 
  retval=$?
  echo Error $retval
  [ -n "$1" ] && echo $1
  exit $retval
}

[ $EUID -ne 0 ] && echo "You must be root to run this script." && exit 77

echo -n "---> Checking operating system and architecture ... "
uname -srp | grep 'Darwin 6.[0-9] powerpc' || die "This doesn't look like an OS X 10.2 install."

echo -n "---> Backing up current /usr/share/zoneinfo ... "
mkdir -m0755 /usr/share/zoneinfo.orig.$$ || die "Couldn't create backup directories."
ditto /usr/share/zoneinfo /usr/share/zoneinfo.orig.$$ || die "Couldn't backup zoneinfo files."
echo /usr/share/zoneinfo.orig.$$

echo -n "---> Creating working directory ... "
WORKDIR="${TMPDIR:=/tmp}/jaguartz.$$"
mkdir -m0755 "$WORKDIR" && cd "$WORKDIR" || die "Couldn't make working directory in $TMPDIR."
echo "$WORKDIR"

echo
echo "---> Patching zoneinfo files ***"
echo

echo -n "---> Downloading ftp://elsie.nci.nih.gov/pub/tzdata$OLSON.tar.gz ... "
curl -sO ftp://elsie.nci.nih.gov/pub/tzdata$OLSON.tar.gz || die "Couldn't download tzdata."
echo OK

echo -n "---> Untarring tzdata$OLSON.tar.gz ... "
mkdir tzdata$OLSON && tar Cxzf tzdata$OLSON tzdata$OLSON.tar.gz || die "Couldn't untar tzdata."
echo OK

echo -n "---> Moving non-zonefiles out of the way ... "
mv tzdata$OLSON/*.tab tzdata$OLSON/leapseconds tzdata$OLSON/yearistype.sh . || die "Couldn't move files."
echo OK

echo -n "---> Compiling new zoneinfo ... "
zic -y ./yearistype.sh tzdata$OLSON/* || die "zic(8) failed."
echo OK

echo
echo "---> Done. Working directory $WORKDIR will be left in place."
echo "---> A reboot is highly recommended to ensure all processes are using the updated timezone data."
echo
