# ******************************
# *       S E T T I N G S      *
# ******************************

# default target
TARGET  ?= linux-release
ifeq ($(filter %-release,$(TARGET)),)
RELEASE := debug
else
RELEASE := release
endif

# check whether we compile for Windows: TARGET-Variable starts with 'win'
ifneq ($(filter win%,$(TARGET)),)
	WIN := yes
endif

# libxml2 settings
XML2CONF ?= xml2-config
LIBXML2_INC := $(shell $(XML2CONF) --cflags)
ifneq ($(filter macos%,$(TARGET)),)
  # Don't mess up the compiler's include hierarchy
  SDKROOT := $(shell xcrun --show-sdk-path)
  LIBXML2_INC := $(filterout -I$(SDKROOT)/usr/include, $(LIBXML2_INC))
endif
LIBXML2_INC := $(patsubst -I/%, -isystem /%, $(LIBXML2_INC))

# compiler setting
ifeq ($(RELEASE),debug)
CFLAGS := -O0 -ggdb3 -fno-inline -fno-default-inline
else
CFLAGS   ?= -O2 -ggdb3
CPPFLAGS += -DNDEBUG
endif
CFLAGS   += -Wall -pipe
CXXFLAGS += $(EXTERNAL_CFLAGS) $(CFLAGS) -std=gnu++17 # -fno-rtti -fno-exceptions

CPPFLAGS += $(LIBXML2_INC)
ifeq ($(WIN),yes)
  ifeq ($(SHARED),)
     CPPFLAGS += -DLIBXML_STATIC # the MinGW libxml2 requires this; otherwise linker problems
  endif
endif

ifneq ($(COMPILE_TARGET),)
CFLAGS += -target $(COMPILE_TARGET)
endif

# ******************************
# *       S O U R C E S        *
# ******************************

# library file
LIBDIR := lib/$(TARGET)
LIB := $(LIBDIR)/libacmodel.a

CCSOURCES := $(wildcard *.cc) 

OBJECTDIR := ObjFiles/$(TARGET)
OBJECTS := $(addprefix $(OBJECTDIR)/,$(CCSOURCES:.cc=.o))

DEPDIR := DepFiles/$(TARGET)
DEPS := $(addprefix $(DEPDIR)/,$(CCSOURCES:.cc=.d))
# dependency file generation flags for g++; note that "=" is used instead of ":="
DEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.d
DEPFLAGS_SHOW := -MT <file.o> -MMD -MP -MF <file.d>

DIRS := $(OBJECTDIR) $(DEPDIR) $(LIBDIR)

# ******************************
# *      T A R G E T S         *
# ******************************

define _show_target
	@echo "---"
	@echo "Making ACModel library for TARGET=$(TARGET)"
	@echo "  Compiler = $(CXX) $(DEPFLAGS_SHOW) $(CPPFLAGS) $(CXXFLAGS)"
	@echo "---"
endef

all:
	@$(call _show_target)
	@$(MAKE) $(LIB)

showtarget:
	@$(call _show_target)

clean:
	@echo Cleaning ACModel.
	@rm -rf core core.* *~ lib DepFiles ObjFiles

# ******************************
# *       R U L E S            *
# ******************************

$(LIB): $(OBJECTS) 
	@echo "Creating library $@."
	@mkdir -p $(LIBDIR)
	@$(AR) rcs $@  $(OBJECTS)

$(OBJECTDIR)/%.o : %.cc 
	@echo Making object file $@.
	@mkdir -p $(OBJECTDIR) $(DEPDIR)
	@$(CXX) $(DEPFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

include $(wildcard $(DEPS))

.phony: all clean showtarget
