#
# Makefile for libtrie v1.0
#
# Copyright (C) 2025-2026 by Robert Cousins.  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# $Id: Makefile,v 1.3 2026/11/05 17:05:49 rec Exp $
#
# Author:  Robert Cousins
# Purpose: Builds static and shared libraries for the CLI autocompletion trie
#          library, its tests, examples and manual, and rolls the release
#          tarball.  There is no configure script: the uname block below is the
#          whole of the configuration.
#
# Targets:
#   all           - Build both static and shared libraries
#   lib           - Same as all
#   static        - Build static library only (libtrie.a)
#   shared        - Build shared library only (libtrie.so)
#   examples      - Build trie_demo and trie_example (alias: demo)
#   tests         - Build the test programs
#   test, check   - Build and run the tests; exits non-zero on any failure
#   sanitize-test - Run the tests under ASan and UBSan
#   tsan-test     - Run the thread test under TSan
#   bench         - Build trie_bench
#   man           - Lint the man page, if mandoc is available
#   manual        - Build the PDF manual
#   docs          - man and manual
#   install       - Install library, header, man page and manual
#   uninstall     - Remove what install put there
#   clean         - Remove build artifacts, but not the shipped PDF
#   distclean     - Also remove the PDF and tarball
#   dist, release - Create the distributable tar file
#
# Honours CC, CFLAGS, LDFLAGS, PREFIX and DESTDIR.  CFLAGS may be replaced
# freely: -fPIC, -I. and -std= are in ALL_CFLAGS, not CFLAGS.
#
# Versions:
#   1.0.0  2025-11-12  Robert Cousins  Initial Makefile.
#   1.1.0  2026-11-04  Robert Cousins  Default CC is cc, for FreeBSD.  make test
#                                      reports failure through its exit status.
#                                      Added uninstall, DESTDIR-clean install,
#                                      FreeBSD soname, sanitizer targets, and a
#                                      clean that leaves the PDF.  ldconfig no
#                                      longer run against a staging directory,
#                                      or on FreeBSD without -m, where a bare
#                                      directory replaces the search path.
#                                      Ships and installs LICENSE.
#

# Compiler and tools
CC ?= cc
AR ?= ar
RANLIB ?= ranlib
INSTALL ?= install

# Compiler flags
CSTD = -std=c17
CWARN = -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes
CFLAGS ?= -O2 -g
ALL_CFLAGS = $(CSTD) $(CWARN) -I. -fPIC $(CFLAGS)
LDFLAGS ?=

# Library naming
LIB_NAME = trie
LIB_VERSION_MAJOR = 1
LIB_VERSION_MINOR = 1
LIB_VERSION_PATCH = 0
LIB_VERSION = $(LIB_VERSION_MAJOR).$(LIB_VERSION_MINOR).$(LIB_VERSION_PATCH)

# Platform detection
UNAME_S := $(shell uname -s)
SHARED_EXT = so
SHARED_LIB = lib$(LIB_NAME).$(SHARED_EXT).$(LIB_VERSION)
SHARED_LINK = lib$(LIB_NAME).$(SHARED_EXT)
SHARED_MAJOR = $(SHARED_LINK).$(LIB_VERSION_MAJOR)
SHARED_FLAGS = -shared -Wl,-soname,$(SHARED_MAJOR)
ifeq ($(UNAME_S),Darwin)
    SHARED_LIB = lib$(LIB_NAME).$(LIB_VERSION).dylib
    SHARED_LINK = lib$(LIB_NAME).dylib
    SHARED_MAJOR = lib$(LIB_NAME).$(LIB_VERSION_MAJOR).dylib
    SHARED_FLAGS = -dynamiclib -install_name $(PREFIX)/lib/$(SHARED_MAJOR)
endif

# Source files
SRCS = trie_core.c trie_complete.c trie_memory.c
OBJS = $(SRCS:.c=.o)
HEADERS = trie.h trie_internal.h
STATIC_LIB = lib$(LIB_NAME).a

# Test programs, in the order they run
TESTS = test_trie test_regress test_limits test_oom test_thread test_fuzz
EXAMPLES = trie_demo trie_example
BENCH = trie_bench

# Every function in the man page gets a link to it
MAN = trie.3
MAN_LINKS = trie_alloc.3 trie_free.3 trie_insert.3 trie_remove.3 \
            trie_contains.3 trie_complete.3 trie_free_completions.3 \
            trie_complete_cb.3 trie_string_count.3 trie_node_count.3 \
            trie_memory_usage.3 trie_version.3

MANUAL = trie_manual.pdf

# Installation directories
PREFIX ?= /usr/local
DESTDIR ?=
LIBDIR ?= $(PREFIX)/lib
INCDIR ?= $(PREFIX)/include
MANDIR ?= $(PREFIX)/share/man
DOCDIR ?= $(PREFIX)/share/doc/libtrie

DISTDIR = libtrie-$(LIB_VERSION)
DISTFILES = Makefile LICENSE README.md RELEASE_v$(LIB_VERSION).md DESIGN.md \
            TRIE_VS_AC.md $(SRCS) $(HEADERS) trie.3 trie_manual.tex \
            $(MANUAL) trie_demo.c trie_example.c trie_bench.c \
            $(TESTS:=.c)

.PHONY: all lib static shared examples demo tests test check check-symbols \
        sanitize-test tsan-test bench man manual docs install uninstall \
        clean distclean dist release help

# Default target
all: static shared
lib: all

# Static library
static: $(STATIC_LIB)

$(STATIC_LIB): $(OBJS)
	$(AR) rcs $@ $(OBJS)
	$(RANLIB) $@

# Shared library
shared: $(SHARED_LIB)

$(SHARED_LIB): $(OBJS)
	$(CC) $(SHARED_FLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS)
	ln -sf $(SHARED_LIB) $(SHARED_LINK)
	ln -sf $(SHARED_LIB) $(SHARED_MAJOR)

# Object files
%.o: %.c $(HEADERS)
	$(CC) $(ALL_CFLAGS) -c $< -o $@

# Programs link the static library by name, so that they test this tree and not
# an installed copy, and so that they need no library path to run.
test_oom: test_oom.c $(HEADERS) $(STATIC_LIB)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -Wl,--wrap=malloc,--wrap=free,--wrap=calloc,--wrap=realloc,--wrap=strdup -o $@ test_oom.c $(STATIC_LIB)

test_thread: test_thread.c $(HEADERS) $(STATIC_LIB)
	$(CC) $(ALL_CFLAGS) -pthread $(LDFLAGS) -o $@ test_thread.c $(STATIC_LIB)

test_%: test_%.c $(HEADERS) $(STATIC_LIB)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -o $@ $< $(STATIC_LIB)

trie_%: trie_%.c trie.h $(STATIC_LIB)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -o $@ $< $(STATIC_LIB)

test_trie_shared: test_trie.c trie.h $(SHARED_LIB)
	$(CC) $(ALL_CFLAGS) $(LDFLAGS) -o $@ test_trie.c -L. -l$(LIB_NAME)

tests: $(TESTS) test_trie_shared
examples: $(EXAMPLES)
demo: examples
bench: $(BENCH)

# Test suite.  Runs everything even after a failure, then fails if any did.
test check: tests examples check-symbols
	@fail=0; \
	for t in $(TESTS); do \
		echo "=== $$t"; \
		./$$t || { echo "*** $$t FAILED"; fail=1; }; \
	done; \
	echo "=== test_trie_shared"; \
	LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH ./test_trie_shared >/dev/null || \
		{ echo "*** test_trie_shared FAILED"; fail=1; }; \
	for e in $(EXAMPLES); do \
		echo "=== $$e"; \
		./$$e >/dev/null || { echo "*** $$e FAILED"; fail=1; }; \
	done; \
	if [ $$fail -eq 0 ]; then echo "All tests passed"; \
	else echo "TESTS FAILED"; exit 1; fi

# Everything the library exports is in trie.h or is marked private.  Names with
# two leading underscores come from a sanitizer's instrumentation.
check-symbols: $(STATIC_LIB)
	@bad=`nm -g $(STATIC_LIB) | awk 'NF == 3 && $$2 != "U" { print $$3 }' | \
	    grep -v '^__' | grep -v '^trie_priv_' | while read s; do \
		grep -q "^$$s(" trie.h || echo $$s; done`; \
	if [ -n "$$bad" ]; then echo "unexpected exported symbols: $$bad"; exit 1; fi

# A failed run still ends with a clean: sanitized objects left behind would
# fail to link in the next plain build.
sanitize-test:
	$(MAKE) clean
	@rc=0; $(MAKE) CFLAGS="-O1 -g -fsanitize=address,undefined -fno-sanitize-recover=undefined -fno-omit-frame-pointer" \
	        LDFLAGS="-fsanitize=address,undefined" test || rc=1; \
	$(MAKE) clean; exit $$rc

# ASLR has to be off for TSan on current Linux kernels.
tsan-test:
	$(MAKE) clean
	@rc=0; $(MAKE) CFLAGS="-O1 -g -fsanitize=thread" LDFLAGS="-fsanitize=thread" test_thread || rc=1; \
	if [ $$rc -eq 0 ]; then \
		if command -v setarch >/dev/null 2>&1; then setarch -R ./test_thread || rc=1; \
		else ./test_thread || rc=1; fi; \
	fi; \
	$(MAKE) clean; exit $$rc

# Documentation
docs: man manual

man: $(MAN)
	@if command -v mandoc >/dev/null 2>&1; then mandoc -Tlint $(MAN) || exit 1; fi

manual: $(MANUAL)

$(MANUAL): trie_manual.tex trie_example.c
	pdflatex -interaction=batchmode trie_manual.tex >/dev/null
	makeindex trie_manual.idx >/dev/null 2>&1
	pdflatex -interaction=batchmode trie_manual.tex >/dev/null
	pdflatex -interaction=batchmode trie_manual.tex >/dev/null

# Installation
install: all
	$(INSTALL) -d $(DESTDIR)$(LIBDIR) $(DESTDIR)$(INCDIR) \
	              $(DESTDIR)$(MANDIR)/man3 $(DESTDIR)$(DOCDIR)
	$(INSTALL) -m 644 $(STATIC_LIB) $(DESTDIR)$(LIBDIR)/
	$(INSTALL) -m 755 $(SHARED_LIB) $(DESTDIR)$(LIBDIR)/
	ln -sf $(SHARED_LIB) $(DESTDIR)$(LIBDIR)/$(SHARED_LINK)
	ln -sf $(SHARED_LIB) $(DESTDIR)$(LIBDIR)/$(SHARED_MAJOR)
	$(INSTALL) -m 644 trie.h $(DESTDIR)$(INCDIR)/trie.h
	$(INSTALL) -m 644 LICENSE $(DESTDIR)$(DOCDIR)/
	$(INSTALL) -m 644 $(MAN) $(DESTDIR)$(MANDIR)/man3/
	for l in $(MAN_LINKS); do \
		ln -sf $(MAN) $(DESTDIR)$(MANDIR)/man3/$$l || exit 1; \
	done
	@if [ -f $(MANUAL) ]; then \
		echo "$(INSTALL) -m 644 $(MANUAL) $(DESTDIR)$(DOCDIR)/"; \
		$(INSTALL) -m 644 $(MANUAL) $(DESTDIR)$(DOCDIR)/; \
	fi
	@if [ -z "$(DESTDIR)" ] && [ "`id -u`" = 0 ]; then \
		case "$(UNAME_S)" in \
		Linux)   ldconfig || true ;; \
		FreeBSD) ldconfig -m $(LIBDIR) || true ;; \
		esac; \
	fi

uninstall:
	rm -f $(DESTDIR)$(LIBDIR)/$(STATIC_LIB)
	rm -f $(DESTDIR)$(LIBDIR)/$(SHARED_LIB)
	rm -f $(DESTDIR)$(LIBDIR)/$(SHARED_LINK)
	rm -f $(DESTDIR)$(LIBDIR)/$(SHARED_MAJOR)
	rm -f $(DESTDIR)$(INCDIR)/trie.h
	rm -f $(DESTDIR)$(MANDIR)/man3/$(MAN)
	for l in $(MAN_LINKS); do rm -f $(DESTDIR)$(MANDIR)/man3/$$l; done
	rm -f $(DESTDIR)$(DOCDIR)/$(MANUAL) $(DESTDIR)$(DOCDIR)/LICENSE
	-rmdir $(DESTDIR)$(DOCDIR) 2>/dev/null

# Clean build artifacts
clean:
	rm -f $(OBJS) $(STATIC_LIB) $(SHARED_LIB) $(SHARED_LINK) $(SHARED_MAJOR)
	rm -f $(TESTS) test_trie_shared $(EXAMPLES) $(BENCH)
	rm -f *.o *~ core
	rm -f trie_manual.aux trie_manual.idx trie_manual.ilg trie_manual.ind
	rm -f trie_manual.log trie_manual.out trie_manual.toc

distclean: clean
	rm -f $(MANUAL) $(DISTDIR).tgz
	rm -rf $(DISTDIR)

# Release packaging.  The tarball ships the PDF, so a reader without LaTeX
# still gets the manual.
dist release: $(MANUAL)
	rm -rf $(DISTDIR) $(DISTDIR).tgz
	mkdir $(DISTDIR)
	cp -p $(DISTFILES) $(DISTDIR)/
	chmod 644 $(DISTDIR)/*
	tar czf $(DISTDIR).tgz $(DISTDIR)
	rm -rf $(DISTDIR)
	@echo "Release package created: $(DISTDIR).tgz"

# Help
help:
	@echo "libtrie v$(LIB_VERSION) - Makefile targets:"
	@echo ""
	@echo "  all            - Build both static and shared libraries (default)"
	@echo "  static         - Build static library (libtrie.a)"
	@echo "  shared         - Build shared library"
	@echo "  examples       - Build trie_demo and trie_example"
	@echo "  test, check    - Build and run all tests"
	@echo "  sanitize-test  - Run all tests under ASan and UBSan"
	@echo "  tsan-test      - Run the thread test under TSan"
	@echo "  bench          - Build trie_bench"
	@echo "  manual         - Build LaTeX documentation (PDF)"
	@echo "  install        - Install library, header, man page and manual"
	@echo "  uninstall      - Remove what install put there"
	@echo "  clean          - Remove build artifacts"
	@echo "  distclean      - Also remove the PDF and tarball"
	@echo "  dist, release  - Create distributable tar file"
	@echo ""
	@echo "Platform detected: $(UNAME_S)"
	@echo "Shared library: $(SHARED_LIB)"
