TARGET_EXEC := hostdox
BUILD_DIR := ./build
SRC_DIRS := ./src

# False targets
# (these are the only ones you manually run)
all: $(TARGET_EXEC)

run: all
	./$(TARGET_EXEC)

clean:
	-rm -r $(BUILD_DIR)
	@echo ""


libs: $(BUILD_DIR)/hid.o $(BUILD_DIR)/libmpdclient.o

submodules:
	git submodule update --init --recursive

.PHONY: clean all run libs submodules

#################################################
# Flags and autodetection

# -MMD and -MP generate makefiles with extension .d.
CPPFLAGS := -MMD -MP \
	-Wall \
	-I src \
	-I libs/hidapi/hidapi \
	-I libs/spdlog/include \
	-I libs/libmpdclient/include \
	-I libs/libmpdclient/output \
	$(shell pkg-config --cflags hunspell)

# udev: required by hidapi
LDFLAGS := \
	-l fftw3 \
	-l udev \
	$(shell pkg-config --libs hunspell)

# Find all cpp files in source dirs
SRCS := $(shell find $(SRC_DIRS) -name '*.cpp')
# Turns src/a.cpp into build/src/a.cpp.o
SRC_OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
LIB_OBJS := $(BUILD_DIR)/hid.o $(BUILD_DIR)/libmpdclient.o
OBJS = $(SRC_OBJS) $(LIB_OBJS)
# Turns build/a.cpp.o into build/a.cpp.d
DEPS := $(OBJS:.o=.d)

#################################################
# Build targets


### Libraries

# Build hidapi
$(BUILD_DIR)/hid.o:
	@mkdir -p $(BUILD_DIR)

	@echo "Compiling hid.o"
	@gcc -Wall -g -fpic -c \
		-I libs/hidapi/hidapi \
		`pkg-config libusb-1.0 --cflags` \
		libs/hidapi/linux/hid.c \
		-o $(BUILD_DIR)/hid.o


# Build libmpdclient
$(BUILD_DIR)/libmpdclient.o:
	@mkdir -p $(BUILD_DIR)

	@cd libs/libmpdclient && \
		meson . output && \
		ninja -C output

	ln -s ../libs/libmpdclient/output/libmpdclient.so $(BUILD_DIR)/libmpdclient.o


### Source

# C++ build step
$(BUILD_DIR)/%.cpp.o: %.cpp
	mkdir -p $(dir $@)
	g++ $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@


# Final build step
$(TARGET_EXEC) : $(OBJS)
	g++ $(OBJS) -o $@ $(LDFLAGS)

# Include generated makefiles
-include $(DEPS)