#!/usr/bin/make -f
# -*- makefile -*-
#export DH_VERBOSE=1

IV_SRC_DIR = $(CURDIR)/ivhines

# when NEURON installs itself into the same location as IV, it will remove all
# of IV's files - so we do this trick, which also allows us to easily filter which
# components of IV we ship in the final package later.
IV_INSTALL_DIR = $(CURDIR)/debian/tmp_iv

INSTALL_DIR = $(CURDIR)/debian/tmp

%:
	dh $@ --with python3

override_dh_auto_configure:
	# we need to build InterViews first, then we can configure NEURON
	:

override_dh_auto_build:
	dh_auto_configure --sourcedirectory=$(IV_SRC_DIR)
	dh_auto_build --sourcedirectory=$(IV_SRC_DIR)
	dh_auto_install --sourcedirectory=$(IV_SRC_DIR) --destdir=$(IV_INSTALL_DIR)

	mv $(CURDIR)/src/mesch $(CURDIR)/src/tmp_mesch
	dh_auto_configure -- \
			--exec_prefix=/usr/lib/neuron/ \
			--with-iv=$(IV_INSTALL_DIR)/usr/lib/$(DEB_HOST_MULTIARCH) \
			--with-readline=/usr/lib/$(DEB_HOST_MULTIARCH) \
			--with-paranrn \
			--with-nrnpython=/usr/bin/python3 \
			--enable-pysetup='--verbose --home=$(INSTALL_DIR)/usr'
	dh_auto_build
	mv $(CURDIR)/src/tmp_mesch $(CURDIR)/src/mesch

override_dh_auto_install:
	dh_auto_install --destdir=$(INSTALL_DIR)

	mkdir $(INSTALL_DIR)/usr/lib/$(DEB_HOST_MULTIARCH)/ivhines/
	cp -a $(IV_INSTALL_DIR)/usr/lib/$(DEB_HOST_MULTIARCH)/*.so.* $(INSTALL_DIR)/usr/lib/$(DEB_HOST_MULTIARCH)/ivhines/

	# the .la files are needed by nrnivmodl and possibly other tools compiling NEURON models
	sed -i "/dependency_libs/ s/'.*'/''/" `find $(INSTALL_DIR)/usr/lib/$(DEB_HOST_MULTIARCH)/ -name '*.la'`

	# duplicates and arch-dependent
	rm -r $(INSTALL_DIR)/usr/share/nrn/lib/python

	# don't ship these extra binaries
	rm $(INSTALL_DIR)/usr/lib/neuron/bin/memacs
	rm $(INSTALL_DIR)/usr/lib/neuron/bin/neurondemo

	# remove (unneeded? misplaced?) header
	rm $(INSTALL_DIR)/usr/lib/*/nrnconf.h

	# fix Python interface location
	mkdir -p $(INSTALL_DIR)/usr/lib/python3/dist-packages/
	mv $(INSTALL_DIR)/usr/lib/python/* $(INSTALL_DIR)/usr/lib/python3/dist-packages/
	rmdir $(INSTALL_DIR)/usr/lib/python/

	# add links to important NEURON binaries
	mkdir -p $(INSTALL_DIR)/usr/bin/
	ln -s /usr/lib/neuron/bin/nrngui $(INSTALL_DIR)/usr/bin/
	ln -s /usr/lib/neuron/bin/nrniv $(INSTALL_DIR)/usr/bin/
	ln -s /usr/lib/neuron/bin/nrnoc $(INSTALL_DIR)/usr/bin/
	ln -s /usr/lib/neuron/bin/nrnivmodl $(INSTALL_DIR)/usr/bin/

	# fix permissions
	chmod -x $(INSTALL_DIR)/usr/lib/neuron/bin/*_makefile

	# fix rpaths
	chrpath -r /usr/lib/$(DEB_HOST_MULTIARCH)/ivhines/ $(INSTALL_DIR)/usr/lib/neuron/bin/ivoc
	chrpath -r /usr/lib/$(DEB_HOST_MULTIARCH)/ivhines/ $(INSTALL_DIR)/usr/lib/neuron/bin/nrniv
	chrpath -r /usr/lib/$(DEB_HOST_MULTIARCH)/ivhines/ $(INSTALL_DIR)/usr/lib/python3/dist-packages/neuron/hoc.cpython*.so

override_dh_auto_clean:
	-rm -r $(IV_INSTALL_DIR)
	-mv $(CURDIR)/src/tmp_mesch $(CURDIR)/src/mesch
	dh_auto_clean

override_dh_missing:
	dh_missing --fail-missing
