#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=-all
export CFLAGS =
export CXXFLAGS =
export LDFLAGS =

COMPILER_FAMILY := gnu15
MPI_FAMILY      := mpich
export MPI_FAMILY
PNAME           := petsc
VERSION         := 3.24.4
INSTALL_PATH    := /opt/ohpc/pub/libs/$(COMPILER_FAMILY)/$(MPI_FAMILY)/$(PNAME)/$(VERSION)
SRCDIR          := $(CURDIR)/$(PNAME)-$(VERSION)
PKG             := $(CURDIR)/debian/$(PNAME)-$(COMPILER_FAMILY)-$(MPI_FAMILY)-ohpc
ENV             := OHPC_MODULES="phdf5 scalapack openblas" bash /build/devel/build-mpi.sh

%:
	dh $@

override_dh_auto_configure:
	test -s SOURCES/$(PNAME)-$(VERSION).tar.gz || \
		wget -q -O SOURCES/$(PNAME)-$(VERSION).tar.gz \
			https://web.cels.anl.gov/projects/petsc/download/release-snapshots/$(PNAME)-$(VERSION).tar.gz
	rm -rf $(SRCDIR)
	tar xf SOURCES/$(PNAME)-$(VERSION).tar.gz

override_dh_auto_build:
	cd $(SRCDIR) && $(ENV) bash -c '\
		unset CFLAGS CXXFLAGS FCFLAGS FFLAGS CC CXX FC F77 F90 LDFLAGS MPI_DIR && \
		python3 ./configure \
			--prefix=$(INSTALL_PATH) \
			--with-cc=mpicc \
			--with-cxx=mpicxx \
			--with-fc=mpif90 \
			--with-f77=mpif90 \
			FFLAGS+="-fPIC" \
			CFLAGS+="-fPIC -DPIC" \
			CXXFLAGS+="-fPIC -DPIC" \
			--with-c-support \
			--with-fortran-interfaces=1 \
			--with-debugging=no \
			--with-shared-libraries \
			--with-mpi=1 \
			--with-batch=0 \
			--with-hdf5=1 \
			--with-hdf5-lib=$$HDF5_LIB/libhdf5.so \
			--with-hdf5-include=$$HDF5_INC \
			--with-scalapack-dir=$$SCALAPACK_DIR \
			--with-blas-lapack-lib=$$OPENBLAS_LIB/libopenblas.so \
			|| cat configure.log && \
		make PETSC_DIR=$$(pwd) PETSC_ARCH=arch-linux-c-opt all -j$$(nproc)'

override_dh_auto_install:
	cd $(SRCDIR) && $(ENV) bash -c '\
		make PETSC_DIR=$$(pwd) PETSC_ARCH=arch-linux-c-opt DESTDIR=$(PKG) install'
	# Fix python shebangs
	cd $(PKG)$(INSTALL_PATH) && \
	for file in \
		lib/petsc/bin/petsc_gen_xdmf.py \
		lib/petsc/bin/PetscBinaryIOTrajectory.py \
		lib/petsc/bin/petscnagfor \
		lib/petsc/bin/taucc.py \
		lib/petsc/bin/petscnagupgrade.py \
		lib/petsc/bin/saws/SAWs.py \
		lib/petsc/bin/petsclogformat.py \
		share/petsc/examples/config/testparse.py \
		share/petsc/examples/config/gmakegen.py \
		share/petsc/examples/config/gmakegentest.py \
		share/petsc/examples/config/report_tests.py; do \
		[ -f "$$file" ] && sed -e "s,/env python.*,/python3,g" -i "$$file" || true; \
	done
	# Remove stock module file
	rm -rf $(PKG)$(INSTALL_PATH)/lib/modules
	# Install modulefile
	mkdir -p $(PKG)/opt/ohpc/pub/moduledeps/$(COMPILER_FAMILY)-$(MPI_FAMILY)/$(PNAME)
	install -m 644 debian/modulefile $(PKG)/opt/ohpc/pub/moduledeps/$(COMPILER_FAMILY)-$(MPI_FAMILY)/$(PNAME)/$(VERSION)

override_dh_auto_clean:
	rm -rf $(SRCDIR)

override_dh_usrlocal:

override_dh_shlibdeps:
	dh_shlibdeps -l$(PKG)$(INSTALL_PATH)/lib -- --ignore-missing-info || true

override_dh_strip:
	dh_strip --no-automatic-dbgsym || true

override_dh_auto_test:
