#!/usr/bin/make -f

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

# magic debhelper rule
%:
	dh  $@  --buildsystem=pybuild

PYTHON3:=$(shell py3versions -vr)

FC:=$(shell basename $(shell readlink /etc/alternatives/f95))
F77:=$(shell basename $(shell readlink /etc/alternatives/f77))
export F77 FC

DO_FLANG:=$(if $(wildcard /usr/bin/flang),true, false)

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
LIBDIR:=/usr/lib/$(DEB_HOST_MULTIARCH)
DESTDIR:=$(CURDIR)/debian/tmp

LD_LIBRARY_PATH:=$(CURDIR)/debian/tmp:$(LD_LIBRARY_PATH)
export LD_LIBRARY_PATH

override_dh_auto_build:
	mkdir -p debian/tmp
	cp debian/aliases.ld Src/aliases.ld
	cp -a Src build-gfortran
	$(MAKE) -C build-gfortran all FC=gfortran
	cp build-gfortran/libsphere-* debian/tmp
	$(DO_FLANG) && \
		 ( cp -a Src build-flang ; \
		$(MAKE) -C build-flang all FC=flang ; \
		cp build-flang/libsphere-* debian/tmp ) || true
	ln -s ../build-$(FC)/libsphere.so Src/libsphere.so
	dh_auto_build

override_dh_auto_install: $(PYTHON3:%=install-python%)
	$(MAKE) -C build-gfortran install DESTDIR=$(DESTDIR) PREFIX=/usr LIBDIR=$(LIBDIR) FC=gfortran
	$(DO_FLANG) && ( $(MAKE) -C build-flang install DESTDIR=$(DESTDIR) PREFIX=/usr LIBDIR=$(LIBDIR) FC=flang ) || true
	strip $(DESTDIR)/$(LIBDIR)/fortran/*/*.a
	dh_auto_install
	dh_numpy3

override_dh_auto_clean:
	dh_clean
	$(MAKE) -C Src clean || echo "No clean target in original Makefile"
	rm -rf build-* Src/aliases.ld build .pybuild

build-python%:
	python$* setup.py build

install-python%:
	python$* setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb

