#!/bin/bash

libcifpp_cache_dir="$1"

# Skip if chemdict_tool is not installed
test -f /usr/bin/chemdict_tool || exit 0

# Skip if components.cif is not in place
test -f "${libcifpp_cache_dir}/components.cif" || exit 0

tmp_dir=$(mktemp --directory)
chown nobody:nogroup "${tmp_dir}"

gzip -c "${libcifpp_cache_dir}/components.cif" > "${tmp_dir}/components.cif.gz"

# lowering privileges in order not to run as root
runuser -u nobody -- /usr/bin/chemdict_tool create "${tmp_dir}/components.cif.gz" "${tmp_dir}/compounds.chemlib" pdb

mv "${tmp_dir}/compounds.chemlib" /var/cache/openstructure/compounds.chemlib
chown root:root /var/cache/openstructure/compounds.chemlib

rm -rf "${tmp_dir}"
