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

SRC     = src/blebus.cpp
LIB     = build/libblebus.a
SO      = build/libblebus.so
TEST    = build/unit_test

PREFIX  = /usr/local

.PHONY: all clean test install uninstall

all: $(LIB) $(SO)

build:
	mkdir -p build

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

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

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

# ── Test build rules ──
#
# BLEBUS-RUNPATH-IS-RELATIVE-SO-CWD-PICKS-THE-LIBRARY — the test links the freshly
# built ARCHIVE, named explicitly, not `-Lbuild -lblebus` 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/libblebus.so; run from anywhere else it found /usr/local/lib/libblebus.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 fix libantheos took.
$(TEST): tests/unit_test.cpp $(LIB) | build
	$(CXX) $(CXXFLAGS) $(INCLUDE) $< -o $@ $(LIB) $(LIBS)

test: $(TEST)
	./$(TEST)

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

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

clean:
	rm -rf build
