# -----------------------------------------------------------------------------
# SPDX-FileCopyrightText: Copyright (c) 2020-2026 Science and Technology
#                         Facilities Council
# SPDX-License-Identifier: BSD-3-Clause
# See the full LICENSE file in the project root for details.
# -----------------------------------------------------------------------------

# This Makefile compiles a PSyData profiling wrapper library using the LFRic
# timer code. It can be used with any code, not only with LFRic.

# ----------- Default "make" values, can be overwritten by the user -----------
# Compiler and compiler flags
F90 ?= gfortran
F90FLAGS ?= -g
# Path to the LFRic infrastructure library. It defaults to the pared-down
# version of the LFRic infrastructure distributed with PSyclone.
# Overwrite for a different infrastructure version.
LFRIC_PATH ?= ./../../../external/lfric_infrastructure/src
# -----------------------------------------------------------------------------

INF_LIB_NAME = lfric
INF_LIB = $(LFRIC_PATH)/lib$(INF_LIB_NAME).a

include $(LFRIC_PATH)/lfric_include_flags.mk

F90FLAGS += $(LFRIC_INCLUDE_FLAGS)

PSYDATA_LIB_NAME = psy_lfric_timer
PSYDATA_LIB = lib$(PSYDATA_LIB_NAME).a
PSYDATA_STANDALONE_LIB_NAME = psy_lfric_timer_standalone
PSYDATA_STANDALONE_LIB = lib$(PSYDATA_STANDALONE_LIB_NAME).a

PSY_OBJS = profile_psy_data_mod.o
INF_OBJS = utilities/timer_mod.o utilities/log_mod.o scalar/scalar_mod.o \
	       utilities/lfric_mpi_mod.o io/io_utility_mod.o \
	       utilities/traceback_mod.o
INF_OBJS_FULL_PATH = $(patsubst %,$(LFRIC_PATH)/%,$(INF_OBJS))

.phony: default clean allclean

default: $(PSYDATA_LIB) $(PSYDATA_STANDALONE_LIB)

# First target: this needs to be linked with the LFRic
# infrastructure library.
$(PSYDATA_LIB): $(INF_LIB) $(PSY_OBJS)
	ar rs $@ $^

# Second target: this library contains the required files
# from the infrastructure library, and can be used by any
# application, not only LFRic.
$(PSYDATA_STANDALONE_LIB): $(INF_LIB) $(PSY_OBJS)
	ar rs $@ $(INF_OBJS_FULL_PATH) $(PSY_OBJS)

# Trigger recompilation if the infrastructure lib is changed
$(PSY_OBJS): $(INF_LIB)

# Create infrastructure library
$(INF_LIB):
	$(MAKE) -C $(LFRIC_PATH)

%.o: %.F90
	$(F90) $(F90FLAGS) -c $<

clean:
	rm -f $(PSYDATA_LIB) $(PSYDATA_STANDALONE_LIB) *.mod *.o

allclean: clean
	$(MAKE) -C $(LFRIC_PATH) allclean
