CXX      := g++
CC       := gcc
PKGFLAGS := $(shell pkg-config --cflags libuv openssl vips)
PKGLIBS  := $(shell pkg-config --libs libuv openssl vips)

BUILD_DIR := build
BINARY    := jtlsrv

CXXFLAGS  := -std=c++17 -Wall -Wextra -Isrc -Ivendor $(PKGFLAGS)
CFLAGS    := -Wall -Ivendor
LDFLAGS   := $(PKGLIBS) -lodbc -pthread

ifeq ($(DEBUG),1)
  CXXFLAGS := -std=c++17 -Wall -Wextra -g -O0 -Isrc -Ivendor $(PKGFLAGS)
  CFLAGS   := -Wall -g -O0 -Ivendor
else
  CXXFLAGS += -O2
  CFLAGS   += -O2
endif

CPP_SRCS := \
  src/main.cpp \
  src/log.cpp \
  src/http.cpp \
  src/tls_server.cpp \
  src/pairing.cpp \
  src/router.cpp \
  src/endpoints/client.cpp \
  src/endpoints/init.cpp \
  src/endpoints/category.cpp \
  src/endpoints/product.cpp \
  src/endpoints/productcomposite.cpp \
  src/endpoints/deleted_entity.cpp \
  src/endpoints/customergroup.cpp \
  src/endpoints/order.cpp \
  src/endpoints/pimage.cpp \
  src/endpoints/cimage.cpp \
  src/db/pool.cpp \
  src/queries/shop.cpp \
  src/request_log.cpp \
  src/order_log.cpp

C_SRCS := \
  vendor/llhttp.c \
  vendor/api.c \
  vendor/http.c

CPP_OBJS := $(patsubst src/%.cpp,$(BUILD_DIR)/src/%.o,$(CPP_SRCS))
C_OBJS   := $(patsubst vendor/%.c,$(BUILD_DIR)/vendor/%.o,$(C_SRCS))
OBJS     := $(CPP_OBJS) $(C_OBJS)

.PHONY: all debug clean rebuild run help

all: $(BINARY)

debug:
	$(MAKE) DEBUG=1 all

$(BINARY): $(OBJS)
	@mkdir -p $(BUILD_DIR)
	$(CXX) $(OBJS) -o $@ $(LDFLAGS)

$(BUILD_DIR)/src/%.o: src/%.cpp
	@mkdir -p $(dir $@)
	$(CXX) $(CXXFLAGS) -c $< -o $@

$(BUILD_DIR)/vendor/%.o: vendor/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

clean:
	rm -rf $(BUILD_DIR) $(BINARY)

rebuild: clean all

run: all
	@mkdir -p logs
	./$(BINARY)

help:
	@echo "Usage: make [target]"
	@echo ""
	@echo "  all      Build $(BINARY) (default)"
	@echo "  debug    Build with -g -O0"
	@echo "  clean    Remove $(BUILD_DIR)/"
	@echo "  rebuild  clean + all"
	@echo "  run      Build and start the server"
	@echo ""
	@echo "Variables: DEBUG=1"
