# --*- Makefile -*--

MAKECONF_FILES = ${filter-out %~, ${wildcard Makeconf*}}

ifneq ("${MAKECONF_FILES}","")
include ${MAKECONF_FILES}
endif

PKG_LIB_DIR ?= .
PKG_PATH    ?=
MODULE_NAME ?= ${notdir $(shell pwd)}

SWIG_MODULE  = ${PKG_LIB_DIR}/${PKG_PATH}/${MODULE_NAME}.pm
SWIG_SO_FILE = ${PKG_LIB_DIR}/auto/${PKG_PATH}/${MODULE_NAME}/${MODULE_NAME}.so

SWIG_SOURCE   = source.c
SWIG_WRAPPER  = ${SWIG_SOURCE:%.c=%_wrap.c}
SWIG_INP_FILE = ${SWIG_SOURCE:%.c=%.i}
OBJ              = ${SWIG_SOURCE:%.c=%.o}
SWIG_WRAPPER_OBJ = ${SWIG_WRAPPER:%.c=%.o}

SPGLIB_DIR = ../../../../externals/spglib
SPGLIB_A   = ${SPGLIB_DIR}/build/libsymspg.a

OBJS = ${OBJ} ${SWIG_WRAPPER_OBJ} ${SPGLIB_A}

vendorarch = $(shell perl -le 'use Config; my $$p = $$Config{vendorarch}; $$p =~ s/^\/usr//; print $$p')
vendorlib  = $(shell perl -le 'use Config; my $$p = $$Config{vendorlib}; $$p =~ s/^\/usr//; print $$p')

all: ${SWIG_MODULE} ${SWIG_SO_FILE}

${SWIG_SO_FILE}: ${OBJS}
	${CC} -Wall `perl -MConfig -e 'print $$Config{lddlflags}'` $^ -o $@

${OBJ} ${SWIG_WRAPPER_OBJ}: ${SWIG_SOURCE} ${SWIG_WRAPPER}
	${CC} -Wall -Wno-unused-value \
		-I. -I${SPGLIB_DIR}/src -c \
		`perl -MConfig -e 'print join(" ", @Config{qw(ccflags optimize cccdlflags)}, "-I$$Config{archlib}/CORE")'` \
		$+

${SWIG_WRAPPER} ${SWIG_MODULE}: ${SWIG_INP_FILE} ${SWIG_SOURCE}
	swig -perl5 -Wall -outdir ${PKG_LIB_DIR}/${PKG_PATH}/ $<

${SPGLIB_A}:
	${MAKE} -C ${SPGLIB_DIR}

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

.PHONY: install

install: ${SWIG_MODULE} ${SWIG_SO_FILE}
	mkdir --parents ${PREFIX}/lib/perl5/COD
	mkdir --parents ${PREFIX}/lib/perl5/auto/COD/SPGLib
	install --mode 644 ${SWIG_MODULE} ${PREFIX}/lib/perl5/COD
	install ${SWIG_SO_FILE} ${PREFIX}/lib/perl5/auto/COD/SPGLib

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

clean-SWIG-module:
	rm -f ${SWIG_WRAPPER} ${OBJ} ${SWIG_WRAPPER_OBJ} *~ *.o

cleanAll-SWIG-module:
	rm -f ${SWIG_SO_FILE} ${SWIG_MODULE}

clean: clean-SWIG-module

cleanAll distclean: cleanAll-SWIG-module
