#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

# This has to be exported to make some magic below work.
export DH_OPTIONS

# Which MPI implementation
ifneq (,$(shell ls /usr/share/mpi-default-dev/debian_defaults))
include /usr/share/mpi-default-dev/debian_defaults 
ifneq (,$(findstring $(ARCH_DEFAULT_MPI_IMPL),openmpi))
INCMPI=/usr/include/openmpi
else
INCMPI=/usr/include/lam
endif 
endif

SYRTHES_HOME=usr/lib/syrthes
INSTALL_DIR=$(CURDIR)/debian/syrthes

%:
	dh $@

override_dh_auto_configure:
	dh_testdir

	# Add here commands to compile the package.
	cd $(CURDIR)/bin && SYRTHES_HOME=$(CURDIR) $(MAKE) install
	# convert2syrthes
	make -C src/util/convert2syrthes MED="yes" INCMED="-I$(INCMPI)" LIBMED="-lmedC"

	touch $@

override_dh_clean:
	SYRTHES_HOME=$(CURDIR) $(MAKE) -C $(CURDIR)/bin distclean
	dh_clean

override_dh_install:
	dh_install
	
	set -e; \
	cd $(CURDIR); \
	for dir in bin bin/Linux data example/cylinder example/cylinder/MESH \
	  example/cylinder/RESU example/cylinder/usr include lib/Linux \
	  usr; do \
	  find $$dir -maxdepth 1 -type f -exec install -m a-x "{}" $(INSTALL_DIR)/$(SYRTHES_HOME)/$$dir \; ; \
	done
	install src/util/convert2syrthes/convert2syrthes $(INSTALL_DIR)/usr/bin
	cd $(INSTALL_DIR)/$(SYRTHES_HOME)/bin && chmod a+x syrthes_create_case Linux/syrthes2ensight
	sed -i "s!@SYRTHES_HOME@!/$(SYRTHES_HOME)!g" $(INSTALL_DIR)/$(SYRTHES_HOME)/bin/syrthes_create_case
	sed -i "s!@SYRTHES_HOME@!/$(SYRTHES_HOME)!g" $(INSTALL_DIR)/$(SYRTHES_HOME)/bin/Makefile
	rm -f $(INSTALL_DIR)/$(SYRTHES_HOME)/bin/syrthes.profile
	# Move example dir to /usr/share/doc/syrthes/
	mkdir -p $(INSTALL_DIR)/usr/share/doc/syrthes$(EXPLICIT_VERSION)
	mv $(INSTALL_DIR)/$(SYRTHES_HOME)/example $(INSTALL_DIR)/usr/share/doc/syrthes/
	cd $(INSTALL_DIR)/usr/share/doc/syrthes/example && tar czf cylinder.tar.gz cylinder && rm -fr cylinder

override_dh_link:
	dh_link \
		/$(SYRTHES_HOME)/bin/syrthes_create_case /usr/bin/syrthes_create_case \
		/$(SYRTHES_HOME)/bin/Linux/syrthes2ensight /usr/bin/syrthes2ensight
