#!/bin/sh

# Code updated based on a bug report in Ubuntu:
#   Bug #1999259 reported by Kyler Laird on 2022-12-09

set -e

# Get the effective UID, but do so in a compatible way (we may be running dash)
euid=${EUID:-$(id -u)}

if [ "${euid}" -ne 0 ]; then
	echo "Please run as root"
	exit 1
fi

if [ -f "/etc/libcifpp.conf" ]; then
	. "/etc/libcifpp.conf"
fi

# check to see if we're supposed to run at all
if [ "$update" != "true" ]; then
	exit 0
fi

# if cache directory doesn't exist, exit.
if ! [ -d "/var/cache/libcifpp" ]; then
	echo "Cache directory '/var/cache/libcifpp' does not exist"
	exit 1
fi

# Create a temp file in the right directory and
# make sure it is cleaned up when this script exits

tmpfile=$(mktemp)
trap "rm -f \"${tmpfile}\"" EXIT

update_dictionary() {
	dict=$1
	source=$2

	# Using curl with
	# --location (follow redirects)
	# --silent (no diagnostic output at all)
	# --time-cond (only fetch if source is newer)
	#
	# Output is extracted and written to $tmpfile and when successful 
	# the tmpfile is placed at the desired location and updated is set
	# to true

	curl --silent --location --compressed --time-cond "${dict}" "${source}" | (
		# uncompress the file on the fly, if it is compressed
		if [ "${source%.gz}" != "${source}" ]; then
			gunzip -c > "${tmpfile}" 2>/dev/null
		else
			cat > "${tmpfile}"
		fi
	) && (
		mv "${tmpfile}" "${dict}" && chmod a+r "${dict}"
	) || true
}

# Update the dictionaries

update_dictionary "/var/cache/libcifpp/components.cif" "https://files.wwpdb.org/pub/pdb/data/monomers/components.cif.gz"
update_dictionary "/var/cache/libcifpp/mmcif_pdbx.dic" "https://mmcif.wwpdb.org/dictionaries/ascii/mmcif_pdbx_v50.dic.gz"
update_dictionary "/var/cache/libcifpp/mmcif_ma.dic" "https://github.com/ihmwg/ModelCIF/raw/master/dist/mmcif_ma.dic"

# notify subscribers, using find instead of run-parts to make it work on FreeBSD as well

if [ -d "/etc/libcifpp/cache-update.d" ]; then
	find "/etc/libcifpp/cache-update.d" \
		-exec test -x {} \; -and -not -exec test -d {} \; \
		-exec {} "/var/cache/libcifpp" \;
fi

exit 0
