#!/usr/bin/make -f

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

CPU:=$(shell dpkg-architecture -qDEB_HOST_ARCH_CPU)
DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

FC:=$(shell basename $(shell readlink -f /usr/bin/f95))
# libeccodes-dev 等依赖包的 Fortran 模块(.mod)按 Debian fortran-mod 约定安装在
# /usr/lib/<triplet>/fortran/gfortran-mod-N/ 目录（N 为 gfortran 模块格式版本）。
# 构建机上 readlink -f /usr/bin/f95 可能解析出带多架构前缀的名字，导致原先
# FMODDIR 拼出的路径不存在；改为直接探测实际存在的 gfortran-mod-* 目录。
FMODDIR:=$(shell ls -d /usr/lib/$(DEB_HOST_MULTIARCH)/fortran/gfortran-mod-* 2>/dev/null | sort -V | tail -n1)
ifeq ($(strip $(FMODDIR)),)
FMODDIR:= /usr/lib/$(DEB_HOST_MULTIARCH)/fortran/$(FC)
endif
FCFLAGS:= -I$(FMODDIR)

ifeq ($(CPU), amd64)
  export FCFLAGS:= $(FCFLAGS) -mcmodel=medium 
endif
ifeq ($(CPU), arm64)
  export FCFLAGS:= $(FCFLAGS) -mcmodel=large -fno-pie
endif
ifeq ($(CPU), ppc64el)
  export FCFLAGS:= $(FCFLAGS) -mcmodel=large
endif

LC_ALL=C
export LC_ALL

# magic debhelper rule
%:
	dh $@

override_dh_auto_build:
	$(MAKE) -f makefile.gfs_gfortran LDFLAGS="$(LDFLAGS)" FCFLAGS="$(FCFLAGS)"
	rm -f *.o *.mod
	$(MAKE) -f makefile.ecmwf_gfortran LDFLAGS="$(LDFLAGS)" FCFLAGS="$(FCFLAGS)"
	rm -f ./options/SPECIES/spec_overview
	find options -type f -exec chmod -x {} \;

override_dh_auto_clean:
	$(MAKE) -f makefile.gfs_gfortran clean
	$(MAKE) -f makefile.ecmwf_gfortran clean
	rm -f *.mod erf.f90.185r.combine flexpart.gfs flexpart.ecmwf

