CXX ?= g++
AR ?= ar
SERVER_AR ?= $(AR)
-include ../.make-settings
OPT=-Og -g
uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')

# Add -m32 for 32bit builds
ifeq ($(findstring -m32,$(CFLAGS)),-m32)
	CXX+= -m32
endif

.DEFAULT_GOAL := all
SOURCES := $(filter-out generated_wrappers.cpp, $(wildcard *.cpp))
ALL_OBJECTS := $(patsubst %.cpp,%.o,$(SOURCES))
DEPENDS := $(patsubst %.cpp,%.d,$(SOURCES))

# Inherit CFLAGS from parent Makefile
TEST_CFLAGS := $(CFLAGS)

# Hold new gtest test to a high standard
# The -Wframe-larger-than cap must accommodate the compiler-generated static
# initialization function, whose frame grows with the number of TEST_F
# registrations in a file: under -fsanitize=address each registration's
# temporaries get their own redzoned stack slot, roughly 150 bytes per test
# on current toolchains (more on older ones). 128K allows large test files
# while still catching runaway frames in hand-written code.
MORE_WARNINGS=-Wno-variadic-macros \
	-Werror \
	-Wpedantic \
	-Wextra \
	-Wall \
	-Wcast-align \
	-Wframe-larger-than=131072 \
	-Wno-strict-overflow \
	-Wsign-compare \
	-Werror=missing-braces \
	-Werror=init-self \
	-Werror=write-strings \
	-Werror=address \
	-Werror=array-bounds \
	-Werror=char-subscripts \
	-Werror=enum-compare \
	-Werror=empty-body \
	-Werror=main \
	-Werror=nonnull \
	-Werror=parentheses \
	-Werror=return-type \
	-Werror=sequence-point \
	-Werror=uninitialized \
	-Werror=volatile-register-var \
	-Werror=ignored-qualifiers \
	-Wno-unused-function \
	-Wno-missing-field-initializers \
	-Wdouble-promotion \
	-Wformat=2

# Detect compiler
IS_GCC := $(if $(findstring clang,$(CXX)),,$(findstring g++,$(CXX)))

GCC_FLAGS :=

# Only add GCC-only warnings and flags
ifeq ($(IS_GCC),g++)
	# GCC supports these extra warnings and -fno-var-tracking-assignments
	MORE_WARNINGS += -Wsync-nand -Wtrampolines -Werror=logical-op -Werror=aggressive-loop-optimizations
	GCC_FLAGS += -fno-var-tracking-assignments
else
	# Clang: disable warnings that are errors in gtest/gmock
	MORE_WARNINGS += -Wno-deprecated-copy
	MORE_WARNINGS += -Wno-keyword-macro
endif

# Enable -Werror=float-equal only for non-32bit builds.
# On 32bit (-m32), GoogleTest headers trigger -Wfloat-equal
# (e.g., in gtest-printers.h), which would fail the build.
ifneq ($(findstring -m32,$(CFLAGS)),-m32)
	MORE_WARNINGS += -Werror=float-equal
endif

-include $(DEPENDS)

ifdef COVERAGE
	TEST_CFLAGS += -DCOVERAGE_TEST $(COVERAGE_CFLAGS)
endif

ifdef FORCE_RUN_SKIPPED_TESTS
	TEST_CFLAGS+=-DFORCE_RUN_SKIPPED_TESTS
endif

# Track compilation flags to force rebuild when they change
.flags: FORCE
	@echo '$(TEST_CFLAGS)' | cmp -s - $@ || echo '$(TEST_CFLAGS)' > $@

.PHONY: FORCE

# Valkey server library dependencies
VALKEY_SERVER_LIB := ../libvalkey.a
HIREDIS_LIB := ../../deps/libvalkey/lib/libvalkey.a
JEMALLOC_LIB := ../../deps/jemalloc/lib/libjemalloc.a
HDR_HISTOGRAM_LIB := ../../deps/hdr_histogram/libhdrhistogram.a
FPCONV_LIB := ../../deps/fpconv/libfpconv.a
LZ4_LIB := ../../deps/lz4/liblz4.a
TLS_LIBS := ../../deps/libvalkey/lib/libvalkey_tls.a -lssl -lcrypto
PKG_CONFIG ?= pkg-config
GTEST_CFLAGS ?=
GTEST_LIBS   ?=
ifeq ($(strip $(GTEST_LIBS)),)
	GTEST_CFLAGS := $(shell pkg-config --cflags gtest gmock 2>/dev/null)
	GTEST_LIBS   := $(shell pkg-config --libs   gtest gmock 2>/dev/null)
endif

ifeq ($(strip $(GTEST_LIBS)),)
    $(error googletest not found. Install gtest or set GTEST_CFLAGS/GTEST_LIBS explicitly)
endif

ZSTD_LD_LIBS :=

ifeq ($(BUILD_ZSTD),yes)
ifdef ZSTD_PREFIX
	ZSTD_STATIC_ARCHIVE := $(firstword $(wildcard \
	    $(ZSTD_PREFIX)/lib/libzstd.a \
	    $(ZSTD_PREFIX)/lib64/libzstd.a))
	TEST_CFLAGS += -DHAVE_ZSTD -I$(ZSTD_PREFIX)/include
	ZSTD_LD_LIBS := $(ZSTD_STATIC_ARCHIVE)
else
	ZSTD_PKGCONFIG_LIBDIR := $(shell $(PKG_CONFIG) --variable=libdir libzstd 2>/dev/null)
	ZSTD_PKGCONFIG_PCFILEDIR := $(shell $(PKG_CONFIG) --variable=pcfiledir libzstd 2>/dev/null)
	ZSTD_STATIC_ARCHIVE := $(firstword $(wildcard \
	    $(if $(ZSTD_PKGCONFIG_LIBDIR),$(ZSTD_PKGCONFIG_LIBDIR)/libzstd.a) \
	    $(if $(ZSTD_PKGCONFIG_PCFILEDIR),$(abspath $(ZSTD_PKGCONFIG_PCFILEDIR)/..)/libzstd.a)))
	TEST_CFLAGS += -DHAVE_ZSTD $(shell $(PKG_CONFIG) --cflags libzstd)
	ZSTD_LD_LIBS := $(ZSTD_STATIC_ARCHIVE) $(filter-out -lzstd,$(shell $(PKG_CONFIG) --libs --static libzstd))
endif
endif

# On Darwin (macOS), the linker does not support -Wl,--wrap,
# so we manually define __wrap_* and __real_* for each function in wrappers.h.
# by copying all object files into the wrapped/ folder and applying symbol redefinitions.
ifeq ($(uname_S), Darwin)
WRAP_DIR := wrapped
VALKEY_SERVER_WRAP_LIB := $(WRAP_DIR)/wrappedlibvalkey.a
ENGINE_SERVER_WRAP_OBJ := $(addprefix $(WRAP_DIR)/, $(ENGINE_SERVER_OBJ))
TEST_WRAP_OBJ := $(addprefix $(WRAP_DIR)/, $(ALL_OBJECTS))

# Homebrew does not add llvm/bin to PATH by default, so we check the standard
# Homebrew prefix locations for both Apple Silicon (/opt/homebrew) and Intel (/usr/local).
BREW_LLVM_BIN := $(firstword $(wildcard /opt/homebrew/opt/llvm/bin /usr/local/opt/llvm/bin))
ifneq ($(BREW_LLVM_BIN),)
  export PATH := $(BREW_LLVM_BIN):$(PATH)
else
  $(error LLVM tools not found. Install via: brew install llvm)
endif

$(WRAP_DIR):
	@mkdir -p $(WRAP_DIR)

# Turns one object into a wrapped object. When the server is built with -flto,
# which the default -O3 turns on (see OPTIMIZATION in ../Makefile), the objects
# are LLVM bitcode and must be turned into real Mach-O objects first.
#
# We use a compiler for that, not llc. The bitcode carries the version of
# whichever clang produced it, and a Homebrew llc of a different version cannot
# read it: it fails with "error: Invalid record" or "Unsupported stack probing
# method" for every object. $(WRAP_CC) is the compiler that produced the bitcode,
# so it always matches: $(CC) for the server objects and $(CXX) for the test
# objects. No -O flag is passed, because the IR is already optimized and this
# step only needs code generation, which is what llc did.
#
# llvm-nm is passed explicitly: Homebrew LLVM installs no plain 'nm', so 'nm'
# would be Apple's. The CMake build (wrap-objects.py) uses llvm-nm as well.
#
# The steps are joined with && so that a failing step stops the build. With ';'
# a failure in generate-redefine-syms.py left an empty syms file, and
# llvm-objcopy then wrote an object without the renames.
define wrap-object
	@mkdir -p $(dir $@)
	@if file $< | grep -q "LLVM bitcode"; then \
		$(WRAP_CC) -c -x ir $< -o $(WRAP_DIR)/$*_temp.o && \
		python3 generate-redefine-syms.py --nm llvm-nm $(WRAP_DIR)/$*_temp.o > $(WRAP_DIR)/$*-wrap-syms && \
		llvm-objcopy --redefine-syms=$(WRAP_DIR)/$*-wrap-syms $(WRAP_DIR)/$*_temp.o $@ && \
		rm -f $(WRAP_DIR)/$*_temp.o; \
	else \
		python3 generate-redefine-syms.py --nm llvm-nm $< > $(WRAP_DIR)/$*-wrap-syms && \
		llvm-objcopy --redefine-syms=$(WRAP_DIR)/$*-wrap-syms $< $@; \
	fi
	@rm -f $(WRAP_DIR)/$*-wrap-syms
endef

# Wrap server library objects
$(ENGINE_SERVER_WRAP_OBJ): WRAP_CC := $(CC)
$(ENGINE_SERVER_WRAP_OBJ): $(WRAP_DIR)/%.o: ../%.o $(WRAP_DIR) generated_wrappers.o
	$(wrap-object)

# Wrap test objects, so that calls to wrapped functions are redirected to __wrap_*
$(TEST_WRAP_OBJ): WRAP_CC := $(CXX)
$(TEST_WRAP_OBJ): $(WRAP_DIR)/%.o: %.o $(WRAP_DIR) generated_wrappers.o
	$(wrap-object)

$(VALKEY_SERVER_WRAP_LIB): $(VALKEY_SERVER_LIB) $(ENGINE_SERVER_WRAP_OBJ) generated_wrappers.o
	@rm -f $@
	$(SERVER_AR) rcs $@ $(ENGINE_SERVER_WRAP_OBJ)
endif

# Ensure Valkey server library is built
$(VALKEY_SERVER_LIB): make-prerequisites
	cd .. && $(MAKE) libvalkey.a

# Ensure parent prerequisites are built
.PHONY: make-prerequisites
make-prerequisites:
	cd .. && $(MAKE) .make-prerequisites

# Read MALLOC / USE_JEMALLOC setting from parent Makefile
JEMALLOC_CFLAGS := -DUSE_JEMALLOC -isystem../../deps/jemalloc/include
ifeq ($(MALLOC),libc)
	JEMALLOC_CFLAGS :=
	JEMALLOC_LIB :=
endif

LD_LIBS := $(HIREDIS_LIB) \
	$(JEMALLOC_LIB) \
	$(GTEST_LIBS) \
	$(HDR_HISTOGRAM_LIB) \
	$(FPCONV_LIB) \
	$(LZ4_LIB) \
	$(ZSTD_LD_LIBS)

# Add libbacktrace support if enabled
ifeq ($(USE_LIBBACKTRACE),yes)
    TEST_CFLAGS += -DUSE_LIBBACKTRACE
    ifdef LIBBACKTRACE_PREFIX
        TEST_CFLAGS += -I$(LIBBACKTRACE_PREFIX)/include
        LDFLAGS += -L$(LIBBACKTRACE_PREFIX)/lib
    endif
    LD_LIBS += -lbacktrace
endif

# Add TLS libraries if enabled
ifeq ($(BUILD_TLS),yes)
	LD_LIBS += $(TLS_LIBS)
endif

# Compile C++ test files, recompile if generated_wrappers or compiler flags change
%.o: %.cpp generated_wrappers.cpp .flags
	$(CXX) -MD -MP -std=c++17 -faligned-new -Wno-write-strings -fpermissive $(GCC_FLAGS) $(OPT) $(DEBUG) $(TEST_CFLAGS) -Wall -Wno-deprecated-declarations -c \
	-isystem .. -I ../../deps/lua/src/ -I ../../deps/hdr_histogram/ -I ../../deps/fpconv/ $(JEMALLOC_CFLAGS) \
	$(GTEST_CFLAGS) $<

$(ALL_OBJECTS): generated_wrappers.o
$(ALL_OBJECTS): OPT := $(OPT) $(MORE_WARNINGS)

# Obtain the list of function calls for which we are generating mocks using the gmock library.  We assume they are defined in
# wrappers.h and begin with the prefix '__wrap_' (which is required by the linker).  These command line arguments are then
# passed in to g++ during linking.
ifneq ($(wildcard wrappers.h),)
	CMD:=egrep '__wrap_.*\(.*;' wrappers.h | sed 's/__wrap_/@/' | sed 's/[^@]*@\([^(]*\)(.*/\1/' | sort | uniq | xargs -I{} echo "-Wl,--wrap={}" | tr "\n" " "
	OVERRIDES:=$(shell $(CMD))
else
	OVERRIDES:=
endif

# Generate a new set of wrappers every time our header changes.
generated_wrappers.cpp: make-prerequisites wrappers.h generate-wrappers.py
	./generate-wrappers.py

generated_wrappers.o: generated_wrappers.cpp

# Generate the single test binary in parent directory.
ifeq ($(uname_S), Darwin)
valkey-unit-gtests: $(TEST_WRAP_OBJ) generated_wrappers.o $(VALKEY_SERVER_WRAP_LIB) $(FINAL_LIBS)
	$(CXX) -g $(LDFLAGS) -fno-lto \
		-Wall -Wno-deprecated-declarations \
		-o $@ $^ $(LD_LIBS) \
		-lm -pthread -ldl
else
valkey-unit-gtests: $(ALL_OBJECTS) generated_wrappers.o $(VALKEY_SERVER_LIB) $(FINAL_LIBS)
	$(CXX) -g $(LDFLAGS) -fno-lto \
		$(OVERRIDES) \
		-Wall -Wno-deprecated-declarations \
		-o $@ $^ $(LD_LIBS) \
		-lrt -lm -pthread -ldl $(if $(COVERAGE),-lgcov)
endif

.PHONY: all
all: valkey-unit-gtests

.PHONY: test-unit
TEST_ARGS = $(if $(accurate),--accurate) $(if $(large_memory),--large-memory) $(if $(valgrind),--valgrind) $(if $(seed),--seed $(seed))
test-unit: valkey-unit-gtests
	python3 ../../deps/gtest-parallel/gtest_parallel.py ./valkey-unit-gtests --timeout_per_test 300 --gtest_filter=$(UNIT_TEST_PATTERN)* -- $(TEST_ARGS)
	@printf '\033[32mAll UNIT TESTS PASSED!\033[0m\n'

.PHONY: valgrind
valgrind: valkey-unit-gtests
	valgrind $(VALGRIND_ARGS) ./valkey-unit-gtests

clean:
	rm -rf *.o valkey-unit-gtests ../valkey-unit-gtests generated_* $(DEPENDS) .flags wrapped

distclean: clean
	$(MAKE) -C .. distclean

.PHONY: clean distclean
