#!/bin/sh
#
#  This script updates the table of leap seconds used by libiso8601. It reads
#  URL from the file /usr/share/libiso8601/url.local, falling back to
#  /usr/share/libiso8601/url if that fails.
#


# read URL settings file, abort if it doesn't set the correct variables
URL_FILE="/usr/share/libiso8601/url"
source "${URL_FILE}"
[ -e "${URL_FILE}.local" ] && source "${URL_FILE}.local"

if [ -z "${LEAPTABLE_URL}" ]
then
	echo "LEAPTABLE_URL not set." >&2 
	exit 1
fi


# Writes a message to syslog. The message should be in argument $1.
log() {
	logger -t "iso8601-leaptable" -- "$1"
}


# function which downloads a file, leaving the original intact on error
#  $1 -> URL
#  $2 -> final output destination
wget_safe() {
	local tmpfile destination
	destination="$2"
	tmpfile="$(mktemp)"
	wget -q -O "${tmpfile}" "$1"

	if [ \( $? -ne 0 \) -o \( ! -s "${tmpfile}" \) ]
	then
		log "unable to download file"
		rm -f "${tmpfile}"
		return 1
	fi

	if ! cmp -s "${destination}" "${tmpfile}"
	then
		log "new file retrieved"
		mv "${tmpfile}" "${destination}"
		chmod 0644 "${destination}"
		return 0
	fi

	log "no update necessary"
	rm -f "${tmpfile}"
	return 0
}


# download leap table file
wget_safe "${LEAPTABLE_URL}" "/usr/share/libiso8601/leap-table"
