# Builds the INSEL user blocks in ../src into libInselUB, in the current directory.
# It is installed in INSEL_HOME, and the GUI runs it from insel.work/inselUB/resources:
#   make -f <INSEL_HOME>/makefile
# From this repository: mkdir -p build && make -C build -f ../makefile

sourcesF := $(wildcard ../src/*.f)
sourcesF90 := $(wildcard ../src/*.f90)
sourcesC := $(wildcard ../src/*.cpp)
objects := $(notdir $(sourcesF:.f=.o) $(sourcesF90:.f90=.o) $(sourcesC:.cpp=.o))

MODULE = libInselUB
FCFLAGS = -finit-local-zero -g -Og -c -Wall -Wno-intrinsic-shadow -Wno-integer-division -fno-automatic -fno-underscoring -fdefault-real-8 -fdefault-double-8 -fmessage-length=0
CCFLAGS = -std=c++17 -g -Og -c -Wall -fmessage-length=0

ifeq ($(OS),Windows_NT)
  ARCHITECTURE = Windows
  # INSEL_HOME is set by the installer
  LIBRARY = $(MODULE).dll
  FC = g++
  CC = g++
  L = g++
  RM = del
  FCFLAGS += -m64
  CCFLAGS += -m64
  LFLAGS = -g -m64 -shared -L"$(INSEL_HOME)" -lInselTools -lgfortran
else ifeq ($(shell uname),Linux)
  ARCHITECTURE = Linux
  INSEL_HOME ?= /usr/local/insel
  LIBRARY = $(MODULE).so
  FC = g++
  CC = g++
  L = g++
  RM = rm -f
  FCFLAGS += -m64 -fPIC -std=legacy
  CCFLAGS += -m64 -fPIC
  LFLAGS = -g -m64 -shared -L$(INSEL_HOME) -lInselTools -ldl
else
  ARCHITECTURE = macOS
  INSEL_HOME ?= /usr/local/insel
  LIBRARY = $(MODULE).dylib
  # Same compilers as INSEL itself: gfortran (brew install gcc) for Fortran, clang/libc++ for C++
  FC = $(shell brew --prefix gcc)/bin/gfortran
  CC = clang++
  L = clang++
  RM = rm -f
  export MACOSX_DEPLOYMENT_TARGET = 14.0
  LFLAGS = -g -dynamiclib -Wl,-install_name,@loader_path/$(LIBRARY) -L$(INSEL_HOME) -lInselTools $(INSEL_HOME)/libgfortran.5.dylib
endif

all:
	@echo Compile $(MODULE) for $(ARCHITECTURE)
ifeq ($(OS),Windows_NT)
# A loaded DLL cannot be overwritten, but it can be moved away. Comments must not be indented: cmd.exe would run them.
	@powershell.exe -ExecutionPolicy Bypass -File "$(INSEL_HOME)\ub_helper.ps1"
endif
ifneq ($(sourcesF),)
	@$(FC) $(FCFLAGS) $(sourcesF)
	@echo Fortran user blocks compiled.
endif
ifneq ($(sourcesF90),)
	@$(FC) $(FCFLAGS) $(sourcesF90)
	@echo Fortran90 user blocks compiled.
endif
ifneq ($(sourcesC),)
	@$(CC) $(CCFLAGS) $(sourcesC)
	@echo C++ user blocks compiled.
endif
	@$(L) $(objects) $(LFLAGS) -o $(LIBRARY)
ifeq ($(ARCHITECTURE),macOS)
# INSEL's dylibs use @loader_path install names, which would resolve to this directory instead of INSEL_HOME
	@install_name_tool -change @loader_path/libInselTools.dylib $(INSEL_HOME)/libInselTools.dylib $(LIBRARY)
	@install_name_tool -change @loader_path/libgfortran.5.dylib $(INSEL_HOME)/libgfortran.5.dylib $(LIBRARY)
	@codesign -f -s - $(LIBRARY)
endif
	@echo $(MODULE) completed.
	@$(RM) *.o

clean:
	@$(RM) *.o $(LIBRARY)
