#!/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 @DATA_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 "@DATA_CACHE_DIR@/mmcif_pdbx_v50.dic" "https://mmcif.wwpdb.org/dictionaries/ascii/mmcif_pdbx_v50.dic.gz"
fetch_dictionary "@DATA_CACHE_DIR@/components.cif" "ftp://ftp.wwpdb.org/pub/pdb/data/monomers/components.cif.gz"
