#!/bin/sh

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
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
fi

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

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

	wget -O${dict}.gz ${source}

	# be careful not to nuke an existing dictionary file
	# extract to a temporary file first

	gunzip -c ${dict}.gz > ${dict}-tmp

	# then move the extracted file to the final location

	mv ${dict}-tmp ${dict}

	# and clean up afterwards

	rm ${dict}.gz
}

# fetch the dictionaries

fetch_dictionary "/var/cache/libcifpp/mmcif_pdbx.dic" "https://mmcif.wwpdb.org/dictionaries/ascii/mmcif_pdbx_v50.dic.gz"
fetch_dictionary "/var/cache/libcifpp/components.cif" "https://ftp.wwpdb.org/pub/pdb/data/monomers/components.cif.gz"

wget -O"/var/cache/libcifpp/mmcif_ma.dic" "https://github.com/ihmwg/ModelCIF/raw/master/dist/mmcif_ma.dic"

# notify subscribers, will fail on FreeBSD

if [ -d "/etc/libcifpp/cache-update.d" ] && [ -x /bin/run-parts ]; then
	run-parts --arg "/var/cache/libcifpp" -- "/etc/libcifpp/cache-update.d"
fi
