#!/usr/bin/make -f

# Build with flang first this release
export FC_DEFAULT=flang
export FC_OPTIONAL=gfortran lfortran
export DH_NO_ORIG_LIBS=1

export DH_VERBOSE=1

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

# Hack until dh-dfortran fix in 0.70 
FLANG_FPM_FFLAGS:=$(shell dh_fortran get_env --fc flang-21 | grep FPM_FFLAGS | sed -e s/FPM_FFLAGS=// ) -I/usr/include
FLANG_FPM_LDFLAGS:=$(shell dh_fortran get_env --fc flang-21 | grep FPM_LDFLAGS | sed -e s/FPM_LDFLAGS=// )
GF_FPM_FFLAGS:=$(shell dh_fortran get_env --fc gfortran | grep FPM_FFLAGS | sed -e s/FPM_FFLAGS=// ) -I/usr/include
GF_FPM_LDFLAGS:=$(shell dh_fortran get_env --fc gfortran | grep FPM_LDFLAGS | sed -e s/FPM_LDFLAGS=// )
#FPM_FC=flang-21
export FPM_FFLAGS FPM_FC FPM_LDFLAGS

# Necessary to build shared libraries
export DEB_LDFLAGS_MAINT_APPEND=-fPIC

# The magic debhelper  rule
%:
	dh $@ --with fortran --buildsystem fortran

execute_after_dh_auto_clean:
	rm -fr doc/html debian/tmp-*

override_dh_auto_build:
	( FPM_FFLAGS="$(FLANG_FPM_FFLAGS)" FPM_LDFLAGS="$(FLANG_FPM_LDFLAGS)"  \
	FPM_FC=flang-21 fpm install --prefix debian/tmp-flang --compiler flang-21 --profile release	--verbose ) 
	( FPM_FFLAGS="$(GF_FPM_FFLAGS)" FPM_LDFLAGS="$(GF_FPM_LDFLAGS)"  \
	FPM_FC=gfortran fpm install --prefix debian/tmp-gfortran --compiler gfortran --profile release	--verbose ) 

execute_after_dh_auto_build:
	ford ford.md

# FTB on error: loc("/home/alastair/git/deb-packages/fortran-julienne/fortran-julienne-3.6.2/test/idiomatic_assertion_failure_test.F90":13:3): flang/lib/Optimizer/Builder/IntrinsicCall.cpp:2033: not yet implemented: coarray: intrinsic this_image
override_dh_auto_test:
	# fpm test --compiler flang-21 --profile release	
	:

execute_before_dh_auto_install:
	patchelf --replace-needed libjulienne.so libjulienne-flang.so.0 debian/tmp-flang/bin/scaffold
	mv debian/tmp-flang/bin/scaffold debian/tmp-flang/bin/fpm-scaffold
