#---*- Makefile -*-------------------------------------------------------
#$Author: saulius $
#$Date: 2019-12-14 10:43:03 +0200 (Sat, 14 Dec 2019) $
#$Revision: 395 $
#$URL: svn+ssh://crystallography.net/home/coder/svn-repositories/polymers-in-COD/trunk/Makelocal-cif-downloads $
#------------------------------------------------------------------------

#*
# A Makefile to dowload CIF files from the COD (or from a local file cache).
#
# USAGE:
#    make downloads
#**

# These variables may be overridden in 'Makeconfig-dirs':

INPUT_DIR ?= inputs
OUTPUT_DIR ?= outputs
DOWNLOAD_DIR ?= ${OUTPUT_DIR}/downloads

# Variables local to this Makefile:

INPUT_LISTS = $(wildcard ${INPUT_DIR}/*.lst)

CIF_DOWNLOAD_LOG = cif-downloads.log

DOWNLOAD_LOGS = ${CIF_DOWNLOAD_LOG}

ifndef CHECK_INPUT_LISTS
define CHECK_INPUT_LISTS
BEGIN{ \
    if(ARGC<2) { \
        print "awk: no identifier list files in the " \
              "\"${INPUT_DIR}/\" directory" \
            > "/dev/stderr"; \
        exit(1) \
    } \
}
endef
endif

DOWNLOAD_DESTINATIONS = \
$(shell awk '${CHECK_INPUT_LISTS} !/^\#/' ${INPUT_LISTS} \
| sort -u | tr " " "\n" \
| awk -F@ '{print ($$2?"revisions/r"$$2"/":"default/")substr($$1,1,1) \
	"/"substr($$1,2,2)"/"substr($$1,4,2)"/"$$1}')

DOWNLOADED_CIFS = ${DOWNLOAD_DESTINATIONS:%=${DOWNLOAD_DIR}/%.cif}

#------------------------------------------------------------------------

CURL ?= curl -k -sSL --fail

.PHONY: downloads distcleancifdownloads

downloads: ${CIF_DOWNLOAD_LOG}

${CIF_DOWNLOAD_LOG}: ${DOWNLOADED_CIFS}
	echo "Downloads completed:" >> $@
	date +"%F %T %Z" >> $@

DOWNLOAD_URL = ${DOWNLOAD_SERVER}/${DOWNLOAD_PREFIX}$(notdir $@)${DOWNLOAD_SUFFIX}

outputs/downloads/revisions/r%.cif:
	@mkdir -p $(dir $@)
	REVISION=$(firstword $(subst /, ,$*)); \
	${CURL} ${DOWNLOAD_URL} > $@; \
	flock ${CIF_DOWNLOAD_LOG} -c 'echo "$$(date +"%F %T %Z") downloaded $@ from '${DOWNLOAD_URL}'"' >> ${CIF_DOWNLOAD_LOG}

outputs/downloads/default/%.cif:
	@mkdir -p $(dir $@)
	REVISION=${REVISION}; \
	${CURL} ${DOWNLOAD_URL} > $@; \
	flock ${CIF_DOWNLOAD_LOG} -c 'echo "$$(date +"%F %T %Z") downloaded $@ from '${DOWNLOAD_URL}'"' >> ${CIF_DOWNLOAD_LOG}

distcleancifdownloads:
	rm -f ${CIF_DOWNLOAD_LOG}
	find outputs/downloads/ -name '*.cif' -print0 \
	| xargs -0 --no-run-if-empty rm -v

distclean cleanAll: distcleancifdownloads
