#!/bin/bash

set -e

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 @CIFPP_CACHE_DIR@ ]; 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 "@CIFPP_CACHE_DIR@/mmcif_pdbx.dic" "https://mmcif.wwpdb.org/dictionaries/ascii/mmcif_pdbx_v50.dic.gz"
fetch_dictionary "@CIFPP_CACHE_DIR@/components.cif" "ftp://ftp.wwpdb.org/pub/pdb/data/monomers/components.cif.gz"

# notify subscribers

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

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