#
# Makefile for libAC v3.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.
#
# Builds both static and shared libraries for the Aho-Corasick string matching
# library with full Tier 1-4 feature support.
#
# Targets:
#   all       - Build both static and shared libraries
#   static    - Build static library only (libAC.a)
#   shared    - Build shared library only (libAC.so or libAC.dylib)
#   tests     - Build and run all test suites; fails if any test fails
#   test,check - Same as tests
#   sanitize-test - Run the test suites under ASan and UBSan
#   demo      - Build demonstration programs
#   benchmark - Build and run performance benchmarks
#   install   - Install library, headers, and man page
#   clean     - Remove all build artifacts
#   release   - Create distributable tar file
#
# $Id: Makefile,v 1.4 2026/11/05 17:05:49 rec Exp $
#
# Author: Robert Cousins
#
# 2025-11-05: Initial Makefile for v3.0 with static and shared library support
# 2026-11-04: 3.1.0: tests exit non-zero on failure and include test_regress
#             and test_fuzz; added sanitize-test; removed dependency lines on
#             the nonexistent ac_v3.h, which broke demo and benchmark; CC can
#             be overridden; reads config.mk; ldconfig only on Linux and never
#             under DESTDIR; clean keeps the shipped manual, distclean does not.
# 2026-11-05: 3.1.0: ships LICENSE; three-clause BSD.
#             Tests and tools link the static library, so that they run from
#             the build tree and cannot pick up an installed libAC.
#

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

# Compiler flags
CFLAGS = -Wall -Wextra -O2 -g -I. -fPIC
CFLAGS_SHARED = -shared
LDFLAGS = -L.
LDFLAGS_PTHREAD = -pthread
EXTRA_CFLAGS ?=
SANFLAGS = -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all

# Settings from ./configure, if it has been run
-include config.mk

# Library naming
LIB_NAME = AC
LIB_VERSION_MAJOR = 3
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)
ifeq ($(UNAME_S),Linux)
    SHARED_EXT = so
    SHARED_LIB = lib$(LIB_NAME).$(SHARED_EXT).$(LIB_VERSION)
    SHARED_LINK = lib$(LIB_NAME).$(SHARED_EXT)
    CFLAGS_SHARED += -Wl,-soname,$(SHARED_LINK).$(LIB_VERSION_MAJOR)
endif
ifeq ($(UNAME_S),Darwin)
    SHARED_EXT = dylib
    SHARED_LIB = lib$(LIB_NAME).$(LIB_VERSION).$(SHARED_EXT)
    SHARED_LINK = lib$(LIB_NAME).$(SHARED_EXT)
    CFLAGS_SHARED = -dynamiclib -install_name $(DESTDIR)/usr/local/lib/$(SHARED_LIB)
endif
ifeq ($(UNAME_S),FreeBSD)
    SHARED_EXT = so
    SHARED_LIB = lib$(LIB_NAME).$(SHARED_EXT).$(LIB_VERSION)
    SHARED_LINK = lib$(LIB_NAME).$(SHARED_EXT)
endif

# Source files
SRCS = ac_core.c ac_pattern.c ac_search.c ac_advanced.c ac_tier4.c
OBJS = $(SRCS:.c=.o)

# Header files
HEADERS = ac.h ac_internal.h

# Static library
STATIC_LIB = lib$(LIB_NAME).a

# Test programs
TESTS = test_basic test_advanced test_tier4 test_regress test_fuzz
TEST_SRCS = test_basic.c test_advanced.c test_tier4.c test_regress.c test_fuzz.c
TEST_OBJS = $(TEST_SRCS:.c=.o)

# Demo and benchmark programs
DEMO = ac_demo tier4_demo
BENCHMARK = ac_benchmark

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

# Default target
.PHONY: all
ifeq ($(ENABLE_SHARED),no)
all: static
else
all: static shared
endif

# Static library
.PHONY: static
static: $(STATIC_LIB)

$(STATIC_LIB): $(OBJS)
	$(AR) rcs $@ $(OBJS)
	$(RANLIB) $@
	@echo "Built static library: $(STATIC_LIB)"

# Shared library
.PHONY: shared
shared: $(SHARED_LIB)

$(SHARED_LIB): $(OBJS)
	$(CC) $(EXTRA_CFLAGS) $(CFLAGS_SHARED) -o $@ $(OBJS)
	@if [ "$(SHARED_LINK)" != "" ]; then \
		ln -sf $(SHARED_LIB) $(SHARED_LINK); \
		if [ "$(UNAME_S)" = "Linux" ]; then \
			ln -sf $(SHARED_LIB) $(SHARED_LINK).$(LIB_VERSION_MAJOR); \
		fi; \
	fi
	@echo "Built shared library: $(SHARED_LIB)"

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

# Test suite
.PHONY: tests test check sanitize-test
tests test check: $(TESTS)
	@echo "=== Running libAC v$(LIB_VERSION) Test Suite ==="
	@fail=0; \
	for t in $(TESTS); do \
		echo ""; \
		if ./$$t; then echo "PASSED: $$t"; \
		else echo "FAILED: $$t"; fail=1; fi; \
	done; \
	echo ""; \
	if [ $$fail -eq 0 ]; then echo "=== All tests passed ==="; \
	else echo "=== SOME TESTS FAILED ==="; fi; \
	exit $$fail

# Run the same suite under ASan and UBSan, then remove the instrumented objects
sanitize-test:
	$(MAKE) clean
	$(MAKE) EXTRA_CFLAGS="$(SANFLAGS)" tests
	$(MAKE) clean

test_basic: test_basic.o $(STATIC_LIB)
	$(CC) $(EXTRA_CFLAGS) -o $@ $< $(STATIC_LIB)

test_advanced: test_advanced.o $(STATIC_LIB)
	$(CC) $(EXTRA_CFLAGS) -o $@ $< $(STATIC_LIB) $(LDFLAGS_PTHREAD)

test_tier4: test_tier4.o $(STATIC_LIB)
	$(CC) $(EXTRA_CFLAGS) -o $@ $< $(STATIC_LIB)

test_regress: test_regress.o $(STATIC_LIB)
	$(CC) $(EXTRA_CFLAGS) -o $@ $< $(STATIC_LIB)

test_fuzz: test_fuzz.o $(STATIC_LIB)
	$(CC) $(EXTRA_CFLAGS) -o $@ $< $(STATIC_LIB)

# Demo programs
.PHONY: demo
demo: $(DEMO)
	@echo "Demo programs ready: $(DEMO)"
	@echo "Run with: ./ac_demo or ./tier4_demo"

ac_demo: ac_demo.o $(STATIC_LIB)
	$(CC) -o $@ $< $(STATIC_LIB)

# Dictionary tools
.PHONY: dict_tools
dict_tools: ac_dict_compile

ac_dict_compile: ac_dict_compile.o $(STATIC_LIB)
	$(CC) -o $@ $< $(STATIC_LIB)
	@echo "Built dictionary compiler: ac_dict_compile"

tier4_demo: tier4_demo.o $(STATIC_LIB)
	$(CC) -o $@ $< $(STATIC_LIB)

# Benchmark
.PHONY: benchmark
benchmark: $(BENCHMARK)
	@echo "Running benchmarks..."
	@./$(BENCHMARK)

$(BENCHMARK): ac_benchmark.o $(STATIC_LIB)
	$(CC) -o $@ $< $(STATIC_LIB)

# Manual
.PHONY: manual
manual: libac_manual.pdf

libac_manual.pdf: libac_manual.tex
	@echo "Building LaTeX manual..."
	pdflatex -interaction=nonstopmode libac_manual.tex > /dev/null
	makeindex libac_manual.idx > /dev/null 2>&1
	pdflatex -interaction=nonstopmode libac_manual.tex > /dev/null
	pdflatex -interaction=nonstopmode libac_manual.tex > /dev/null
	@echo "Manual built: libac_manual.pdf"

# Installation
.PHONY: install
install: all
	@echo "Installing libAC v$(LIB_VERSION)..."
	install -d $(LIBDIR)
	install -d $(INCDIR)
	install -d $(MANDIR)
	install -m 644 $(STATIC_LIB) $(LIBDIR)/
	install -m 755 $(SHARED_LIB) $(LIBDIR)/
	@if [ "$(SHARED_LINK)" != "" ]; then \
		cd $(LIBDIR) && ln -sf $(SHARED_LIB) $(SHARED_LINK); \
		if [ "$(UNAME_S)" = "Linux" ]; then \
			cd $(LIBDIR) && ln -sf $(SHARED_LIB) $(SHARED_LINK).$(LIB_VERSION_MAJOR); \
		fi; \
	fi
	install -m 644 ac.h $(INCDIR)/ac.h
	install -m 644 libac.3 $(MANDIR)/
	@if [ "$(UNAME_S)" = "Linux" ] && [ -z "$(DESTDIR)" ] && \
	    command -v ldconfig >/dev/null 2>&1; then \
		echo "Updating library cache..."; \
		ldconfig $(LIBDIR) 2>/dev/null || true; \
	fi
	@echo "Installation complete."
	@echo "Include with: #include <ac.h>"
	@echo "Link with: -lAC"

# Clean build artifacts
.PHONY: clean
clean:
	rm -f $(OBJS) $(TEST_OBJS)
	rm -f $(STATIC_LIB) $(SHARED_LIB) $(SHARED_LINK) $(SHARED_LINK).$(LIB_VERSION_MAJOR)
	rm -f $(TESTS) $(DEMO) $(BENCHMARK)
	rm -f ac_dict_compile ac_dict_compile.o ac_dict_search ac_dict_search.o
	rm -f dict.c dict.h dict.o
	rm -f ac_demo.o tier4_demo.o ac_benchmark.o
	rm -f *.o *~ core
	rm -f test_ac.dot test_ac_code.c automaton.dat *.dat
	rm -f libac_manual.aux libac_manual.idx libac_manual.ilg libac_manual.ind
	rm -f libac_manual.log libac_manual.out libac_manual.toc
	rm -f libac_manual.loa libac_manual.lof
	@echo "Clean complete."

# Also remove what configure and the manual build produced
.PHONY: distclean
distclean: clean
	rm -f config.mk libac_manual.pdf

# Release packaging
.PHONY: release
release: distclean manual
	@echo "Creating release package: libAC-$(LIB_VERSION).tgz"
	@mkdir -p libAC-$(LIB_VERSION)
	@cp $(SRCS) $(HEADERS) libAC-$(LIB_VERSION)/
	@cp $(TEST_SRCS) ac_demo.c tier4_demo.c ac_benchmark.c libAC-$(LIB_VERSION)/
	@cp ac_dict_compile.c libAC-$(LIB_VERSION)/
	@cp Makefile configure LICENSE libac.3 README_v3.md TIER4_FEATURES.md libAC-$(LIB_VERSION)/
	@cp libac_manual.tex libac_manual.pdf libAC-$(LIB_VERSION)/
	@cp COMPLETE_SUMMARY.txt RELEASE_v3.0.md RELEASE_v3.1.0.md libAC-$(LIB_VERSION)/
	@chmod -R u+w,go+rX libAC-$(LIB_VERSION)
	@tar czf libAC-$(LIB_VERSION).tgz libAC-$(LIB_VERSION)/
	@rm -rf libAC-$(LIB_VERSION)
	@echo "Release package created: libAC-$(LIB_VERSION).tgz"
	@ls -lh libAC-$(LIB_VERSION).tgz

# Help
.PHONY: help
help:
	@echo "libAC v$(LIB_VERSION) - Makefile targets:"
	@echo ""
	@echo "  all        - Build both static and shared libraries (default)"
	@echo "  static     - Build static library (libAC.a)"
	@echo "  shared     - Build shared library (libAC.so/dylib)"
	@echo "  tests      - Build and run all test suites"
	@echo "  sanitize-test - Run the test suites under ASan and UBSan"
	@echo "  distclean  - clean, and remove config.mk and the manual PDF"
	@echo "  demo       - Build demonstration programs"
	@echo "  benchmark  - Build and run performance benchmarks"
	@echo "  manual     - Build LaTeX documentation (PDF)"
	@echo "  install    - Install library, headers, and man page"
	@echo "  clean      - Remove all build artifacts"
	@echo "  release    - Create distributable tar file"
	@echo "  help       - Show this help message"
	@echo ""
	@echo "Platform detected: $(UNAME_S)"
	@echo "Shared library: $(SHARED_LIB)"
