#!/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 /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" "ftp://ftp.wwpdb.org/pub/pdb/data/monomers/components.cif.gz"

# this one is not compressed

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