CXX     = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -Werror -O2 -fPIC
LIBS    = -lpthread
INCLUDE = -Iinclude

SRC     = src/sockbus.cpp
LIB     = build/libsockbus.a
SO      = build/libsockbus.so
TEST    = build/unit_test

PREFIX  = /usr/local

.PHONY: all clean test spec-check install uninstall

all: $(LIB) $(SO)

build:
	mkdir -p build

build/sockbus.o: src/sockbus.cpp include/sockbus.hpp | build
	$(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@

$(LIB): build/sockbus.o
	ar rcs $@ $^

$(SO): build/sockbus.o
	$(CXX) -shared -o $@ $^ $(LIBS)

# ── Test build rules ──
#
# SOCKBUS-RUNPATH-IS-RELATIVE-SO-CWD-PICKS-THE-LIBRARY — the test links the freshly
# built ARCHIVE, named explicitly, not `-Lbuild -lsockbus` with `-Wl,-rpath,build`.
#
# That rpath is RELATIVE, so the loader resolved it against the process's working
# directory rather than the binary's. Run from the project root it found
# build/libsockbus.so; run from anywhere else it found /usr/local/lib/libsockbus.so.
# `$ORIGIN` is the binary-relative form, but the rule already DEPENDED on $(LIB)
# and only the link line disagreed — so naming the archive removes the runtime
# search entirely rather than aiming it. This is the base/antheos fix.
$(TEST): tests/unit_test.cpp $(LIB) | build
	$(CXX) $(CXXFLAGS) $(INCLUDE) $< -o $@ $(LIB) $(LIBS)

# SOCKBUS-SPEC-DOCUMENTS-THE-REMOVED-C-API — the published specification described
# the C11 API for five months under a C++17 label, and every process that should
# have caught it looked at the front matter instead of the body. The v2.0.0 rewrite
# did not touch the spec; a coherence audit three days later changed exactly one
# line, `**Language:** C11` -> `C++17`, which made it worse: an out-of-date C spec
# reads as out of date, while a C spec asserting C++17 reads as the library being C.
# A relicense and a rename passed over it after that.
#
# So the gate is on the BODY, not the label. A C fence or a `sockbus_` identifier in
# the spec means it is describing software that was deleted. This would have failed
# on 2026-03-18.
spec-check:
	@if grep -nE '```c$$' docs/SOCKBUS_SPEC.md; then \
		echo "spec-check: C code fence in the specification (the API is C++17)"; exit 1; fi
	@if grep -nE 'sockbus_[a-z]+\(|\bsockbus_t\b|SOCKBUS_(DEFAULT_SIZE|MAX_NAME|MAX_READERS|READER_NAME_LEN|MAX_MSG_SIZE)' docs/SOCKBUS_SPEC.md; then \
		echo "spec-check: C11 identifier in the specification (the API is C++17)"; exit 1; fi
	@echo "spec-check: OK"

test: spec-check $(TEST)
	./$(TEST)

install: $(LIB) $(SO) include/sockbus.hpp
	install -d $(PREFIX)/lib $(PREFIX)/include
	install -m 644 $(LIB) $(PREFIX)/lib/
	install -m 755 $(SO) $(PREFIX)/lib/
	install -m 644 include/sockbus.hpp $(PREFIX)/include/
	ldconfig

uninstall:
	rm -f $(PREFIX)/lib/libsockbus.a $(PREFIX)/lib/libsockbus.so
	rm -f $(PREFIX)/include/sockbus.hpp
	ldconfig

clean:
	rm -rf build
