# Author Yannis Gerlach
# Hochschule Osnabrück
# 13.11.2020

# `make clean all` nicht mit -j verwenden! -> race condition im make file
# statdessen: `make clean; make all -j` verwenden

NAME = fontbot
NAMETEST = test
CFLAGS = -std=c++17 -O2 -pipe -Wall -Wextra -Wno-unused-parameter -Wpedantic -rdynamic #-march=native -Wall
CXX = g++
SRCF = src/
BUILDDIR = build/
TESTF = tests/
DEPF = $(BUILDDIR)deps/
INCF = ./src/
INCFS = $(shell find $(INCF) -type d)

TP = ./thirdparty/
TAPIF = $(TP)TAPI/
TAPIA = $(TAPIF)libTAPI.a

LOGF = $(TAPIF)Log/
LOGO = $(LOGF)Log.o

INCLUDES = -I$(LOGF) -I$(TAPIF)include/ $(addprefix -I, $(INCFS))
LDFLAGS = -lcurl -lseccomp -lcap

SRCFILES = $(shell find $(SRCF) -name "*.cpp")
OBJFILES = $(patsubst $(SRCF)%, $(BUILDDIR)%, $(patsubst %.cpp, %.o, $(SRCFILES))) $(LOGO)
DEPFILES = $(wildcard $(DEPF)*.d)

SOURCEDIRS = $(shell find $(SRCF) -type d -printf "%p/\n")
BUILDDIRS = $(patsubst $(SRCF)%, $(BUILDDIR)%, $(SOURCEDIRS))

OBJFILESTEST = $(filter-out $(BUILDDIR)main.o, $(OBJFILES))

INCLUDES += $(addprefix -I, $(SOURCEDIRS))

all: $(NAME) runtest

$(NAME): $(BUILDDIRS) $(DEPF) $(OBJFILES) $(TAPIA)
	@echo "Linking $@"
	@$(CXX) $(CFLAGS) -o $@ $(filter %.o, $^) $(filter %.a, $^) $(LDFLAGS)

$(BUILDDIR)%.o: $(SRCF)%.cpp
	@echo "Compiling: $@"
	@$(CXX) $(CFLAGS) $(INCLUDES) $< -MM -MT $@ > $(DEPF)$(subst /,_,$*).d
	@$(CXX) -c -o $@ $(CFLAGS) $(INCLUDES) $<

$(NAME)_strip: $(NAME)
	@echo "Strip $<"
	@strip -o $@ $<

%/:
	mkdir -p $@

clean-depends:
	$(RM) -r $(DEPF)

$(LOGO):
	$(MAKE) -C $(LOGF) all

$(TAPIA):
	$(MAKE) -C $(TAPIF) libTAPI.a

clean:
	$(RM) -r $(NAME) $(BUILDDIR) $(NAMETEST) $(NAME)_strip
	$(MAKE) -C $(LOGF) $@
	$(MAKE) -C $(TAPIF) $@

$(NAMETEST): $(BUILDDIRS) $(DEPF) $(TESTF)*.cpp $(OBJFILESTEST) $(TAPIA)
	@echo "Compiling tests"
	$(CXX) -o $@ $(filter %.o, $^) $(filter %.a, $^) $(filter %.cpp, $^) $(CFLAGS) -I$(SRCF) $(INCLUDES) $(LDFLAGS)

runtest: $(NAMETEST)
	@echo "Running tests"
	./$<

.PHONY: clean all $(NAMETEST) clean-depends runtest

include $(DEPFILES)
