#!/usr/bin/make -f

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

# magic debhelper rule
%:
	dh $@ --with python3 

# To aid reproducible builds
LC_ALL=C
export LC_ALL

ARCH:=$(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
LIBDIR:=/usr/lib/$(ARCH)
INSTALLDIR:=$(CURDIR)/debian/tmp

# FC set to f77 by default in make
# Read default compiler name unless FC is actually set
ifeq ($(FC),f77)
  FC:=$(shell basename $(shell readlink /etc/alternatives/f95))
endif

PY3:=$(shell py3versions -d)
PY3nodot:=$(shell py3versions -dv | tr -d '.')

override_dh_auto_build:
	cp debian/platform_specific.mk.debian.$(FC) platform_specific.mk.debian
	cp debian/ef_utility/platform_specific.mk.debian.$(FC) external_functions/ef_utility/platform_specific.mk.debian
	sed -e 's%@ARCH@%${ARCH}%' \
                -e 's%@LIBDIR@%${LIBDIR}%' \
		-e 's%@CURDIR@%${CURDIR}%' \
                -e 's%@INSTALLDIR@%${INSTALLDIR}%' \
                < debian/site_specific.mk.in > site_specific.mk
	cp site_specific.mk external_functions/ef_utility

override_dh_auto_install:
	# Need temp. libraries during build.
	mkdir -p $(INSTALLDIR)/lib/$(PY3)
	ln -s $(CURDIR)/install/lib/$(PY3)/site-packages//pyferret/libpyferret.cpython-$(PY3nodot)-$(ARCH).so \
		$(INSTALLDIR)/lib/$(PY3)/libpyferret.so
	# Build and install 
	# Horrible hack breaks The Debian Way. I'm doing the build in the 'install' phase, as i'm installing into debian/tmp
	# Doing it any earlier, and dh_prep will remove debian/tmp. 
	# This means I'm also doing 'test' after the Install, not between during make & install. gack.
	for p in $(PY3) ; do \
		$(MAKE) HOSTTYPE=debian PYTHON_EXE=$$p clean all install ; \
		done
	find debian \( -name '*.pyo' -o -name '*.pyc' \) -delete
	find debian -type d -name __pycache__ -delete
	dh_numpy3
	@echo "Now doing bench tests"
	ln -s debian/pyferret3  $(INSTALLDIR)/lib/$(PY3)/pyferret
	# First build necessary files
	for p in  $(PY3) ; do \
		sed -e 's%@ARCH@%${ARCH}%' \
                -e 's%@LIBDIR@%${LIBDIR}%' \
		-e 's%@CURDIR@%${CURDIR}%' \
                -e "s%@PYTHON@%$$p%" \
                < debian/site_specific.mk.in > site_specific.mk ; \
		PATH=$(INSTALLDIR)/lib/$$p:$(PATH) PYTHONPATH=$(INSTALLDIR)/lib/$$p/site-packages \
		echo "IGNORING TESTS" ;  \
		done

override_dh_auto_test:
	@echo "Dummy test, to avoid calling make. Do test later"

override_dh_auto_clean:
	# use system xpm.h, not supplied ones
	rm -f fer/gui/xpm*.h
	rm -rf ./build ./install
	find . -type l  -delete 
	find . -name '*.o' -o -name '*.so'  -delete
	[ ! -f platform_specific_flags.mk.debian ]  || $(MAKE)  clean HOSTTYPE=debian 

