CXX = g++
CC = gcc
# LBUF_SIZE: sqlitedb.cpp clamps attribute blobs to it.  Production pulls
# the macro from alloc.h via config/externs; the standalone harness only
# defines TINYMUX_TYPES_DEFINED and never includes that chain (#1868).
# Keep this value equal to mux/include/alloc.h.
#
# -MMD -MP: emit header prerequisites next to each object (#1952).  The rules
# below list headers by hand, which is correct today but drifts the moment a
# source picks up an #include nobody remembers to add here -- and a missed
# header means editing it rebuilds nothing and the suite reports green
# against the previous version.  The hand-written lists stay: they are what
# makes the FIRST build correct, before any .d exists.
CXXFLAGS = -std=c++17 -g -O2 -Wall -Wextra -MMD -MP -DTINYMUX_TYPES_DEFINED -DLBUF_SIZE=32768
CFLAGS = -g -O2 -MMD -MP -DSQLITE_THREADSAFE=1
INCDIR = ../../mux/include
ENGDIR = ../../mux/modules/engine
SQLITEDIR = ../../mux/sqlite
PATH_CHECKS = \
	$(INCDIR)/sqlitedb.h \
	$(INCDIR)/sqlite_backend.h \
	$(INCDIR)/storage_backend.h \
	$(ENGDIR)/sqlitedb.cpp \
	$(ENGDIR)/sqlite_backend.cpp \
	$(SQLITEDIR)/sqlite3.c \
	$(SQLITEDIR)/sqlite3.h

all: check-paths test_sqlitedb test_backend

check-paths:
	@for path in $(PATH_CHECKS); do \
		if [ ! -e "$$path" ]; then \
			echo "ERROR: required DB test dependency not found: $$path"; \
			echo "Update tests/db/Makefile if engine/include/sqlite paths moved."; \
			exit 1; \
		fi; \
	done

sqlite3.o: $(SQLITEDIR)/sqlite3.c $(SQLITEDIR)/sqlite3.h
	$(CC) $(CFLAGS) -I$(SQLITEDIR) -c -o $@ $<

sqlitedb.o: $(ENGDIR)/sqlitedb.cpp $(INCDIR)/sqlitedb.h $(SQLITEDIR)/sqlite3.h
	$(CXX) $(CXXFLAGS) -I$(INCDIR) -I$(SQLITEDIR) -c -o $@ $<

sqlite_backend.o: $(ENGDIR)/sqlite_backend.cpp $(INCDIR)/sqlite_backend.h $(INCDIR)/storage_backend.h $(INCDIR)/sqlitedb.h
	$(CXX) $(CXXFLAGS) -I$(INCDIR) -I$(SQLITEDIR) -c -o $@ $<

test_sqlitedb.o: test_sqlitedb.cpp $(INCDIR)/sqlitedb.h
	$(CXX) $(CXXFLAGS) -I$(INCDIR) -I$(SQLITEDIR) -c -o $@ $<

test_backend.o: test_backend.cpp $(INCDIR)/storage_backend.h $(INCDIR)/sqlite_backend.h $(INCDIR)/sqlitedb.h
	$(CXX) $(CXXFLAGS) -I$(INCDIR) -I$(SQLITEDIR) -c -o $@ $<

stubs.o: stubs.cpp
	$(CXX) $(CXXFLAGS) -c -o $@ $<

test_sqlitedb: test_sqlitedb.o sqlitedb.o sqlite3.o stubs.o
	$(CXX) $(CXXFLAGS) -o $@ $^

test_backend: test_backend.o sqlite_backend.o sqlitedb.o sqlite3.o stubs.o
	$(CXX) $(CXXFLAGS) -o $@ $^

test: check-paths test_sqlitedb test_backend
	./test_sqlitedb
	@echo ""
	./test_backend

clean:
	rm -f *.o *.d test_sqlitedb test_backend

# Generated by -MMD; absent on the first build, hence the leading '-'.
-include $(wildcard *.d)

.PHONY: all check-paths test clean
