# ---------------------------------------------------------------------------
# libcx -- a library for building command-line interfaces, its compiler, and
#          the front end that makes a CLI the whole of an SSH session.
#
# $Id: Makefile,v 1.16 2026/10/26 19:54:09 rec Exp $
#
# Author:  Robert Cousins
# Purpose: Build the library (static and shared), cxgen(1), cx-shell(8), the
#          worked example, the test programs, the man pages and the LaTeX
#          manual, and roll a release tarball.
#
# The release contract: the user downloads libcx-1.01.tar.gz, unpacks it in an
# empty directory, and types
#
#       make ; sudo make install
#
# There is no configure script and no autoconf -- neither is installed on any
# of the machines this package is developed on.  Platform differences are
# handled by the uname-driven block below, which is the whole of the automatic
# configuration this package needs.
#
# Note:    -std=c2x is the newest standard BOTH toolchains accept.  gcc 13.3
#          rejects -std=c23; clang 19.1 accepts c17, c2x and c23.  Every .c
#          also defines _POSIX_C_SOURCE 200809L before its includes, because
#          c2x is strict ISO and otherwise hides read(2) and strdup(3).
#
#          The library objects are compiled -fvisibility=hidden and the public
#          entry points are marked CX_API in <cx/cx.h>.  Hidden symbols are
#          still resolvable when the static archive is linked, so the test
#          programs can reach cx_priv_ internals, while the shared library
#          exports exactly the header's declarations -- which is what
#          tests/t_symbols.sh checks, in both directions.
#
# Versions:
#   1.00  2026-09-07  Robert Cousins  Initial version.
#   1.01  2026-09-22  Robert Cousins  Added tests/t_emitdoc.sh to SHTESTS.
#   1.02  2026-09-22  Robert Cousins  Real man/manual/install/dist targets:
#                                     the three doc/ man pages, the LaTeX
#                                     manual (with cxgen --emit-tex's thermo
#                                     chapter pulled in at build time), and
#                                     the release tarball this package had
#                                     been missing.
#   1.03  2026-09-22  Robert Cousins  Added tests/t_prompt.c, regression
#                                     coverage for a sub-mode's own prompt.
#   1.04  2026-09-23  Robert Cousins  Added examples/notes, the second worked
#                                     example (a CLI backed by SQLite instead
#                                     of a struct in memory).  Its link step
#                                     probes for <sqlite3.h> itself and skips
#                                     the example, rather than failing the
#                                     build, on a machine that lacks it --
#                                     the same treatment `man' already gives
#                                     a missing mandoc/groff.
#   1.05  2026-09-23  Robert Cousins  Added tests/t_greedy.c, regression
#                                     coverage for CX_ATTR_GREEDY now that
#                                     src/cx_parse.c actually implements it.
#   1.06  2026-09-23  Robert Cousins  Added the session-variable API and
#                                     `default $name'.  Added
#                                     tests/t_sessionvar.c (the API alone)
#                                     and tests/t_dyndefault.c against a
#                                     grammar generated from
#                                     tests/t_dyndefault.cx (the compiler
#                                     and the runtime agreeing about it).
#   1.07  2026-09-23  Robert Cousins  Added cx_session_run_init() and the
#                                     `macro' declaration.  Added
#                                     tests/t_initfile.c and tests/t_macro.c,
#                                     each against its own generated grammar,
#                                     following the tests/t_dyndefault.c
#                                     pattern.
#   1.08  2026-09-24  Robert Cousins  Fixed the examples/notes sqlite3.h
#                                     probe: `echo '\#include ...'` passed a
#                                     literal backslash through to the shell,
#                                     so the line never started with `#' and
#                                     the preprocessor never actually tried
#                                     the include -- the probe reported
#                                     "found" unconditionally, on every
#                                     platform, regardless of whether
#                                     sqlite3.h existed.  Every machine this
#                                     was built on before orville happened to
#                                     have the header, which is why this went
#                                     unnoticed.  On orville, which does not,
#                                     `make all' ran the real compile anyway
#                                     and failed hard instead of skipping.
#                                     The backslash was never needed: a `#'
#                                     in a recipe line is not special to
#                                     Make, only in the makefile's own
#                                     top-level syntax.
#   1.09  2026-10-26  Robert Cousins  libcx 1.01.  src/cx_utf8.c; the new
#                                     tests t_utf8, t_ask, t_pager,
#                                     t_limits, t_idle and t_cxshell (the
#                                     last compiling shell/cx_shell.c in, to
#                                     reach its statics); the fuzz harnesses
#                                     -- replay builds for `make test' via
#                                     tests/t_fuzz.sh, libFuzzer builds for
#                                     `make fuzz', a campaign in `make
#                                     fuzz-run'; libcx.pc.in and an
#                                     install-lib target that installs it
#                                     where each platform's pkg-config
#                                     looks, exercised by
#                                     tests/t_install.sh; tests/t_cplusplus.sh,
#                                     a C++ appliance built -pedantic
#                                     -Werror.  VERSION 1.01.
# ---------------------------------------------------------------------------

PKG      = libcx
VERSION  = 1.01
DISTDIR  = $(PKG)-$(VERSION)

# ----- toolchain -----------------------------------------------------------

CC       ?= cc
CSTD     ?= -std=c2x
CWARN    ?= -Wall -Wextra -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes
COPT     ?= -O2
CFLAGS   ?= $(CSTD) $(CWARN) $(COPT)
CPPFLAGS ?= -Iinclude -Isrc
LDFLAGS  ?=
LIBS     ?=
AR       ?= ar
RANLIB   ?= ranlib
INSTALL  ?= install

VIS       = -fvisibility=hidden

# ----- platform detection --------------------------------------------------

UNAME_S := $(shell uname -s)

# Where pkg-config looks differs: FreeBSD's pkgconf searches libdata/, not
# lib/ -- verified on orville with `pkgconf --variable pc_path pkgconf'.
ifeq ($(UNAME_S),Linux)
    PLATFORM_LIBS = -lutil
    SOEXT         = so
    SONAME_FLAG   = -Wl,-soname,
    PCDIR_DEFAULT = $(LIBDIR)/pkgconfig
endif
ifeq ($(UNAME_S),FreeBSD)
    PLATFORM_LIBS = -lutil
    SOEXT         = so
    SONAME_FLAG   = -Wl,-soname,
    PCDIR_DEFAULT = $(PREFIX)/libdata/pkgconfig
endif
ifeq ($(UNAME_S),Darwin)
    PLATFORM_LIBS =
    SOEXT         = dylib
    SONAME_FLAG   = -Wl,-install_name,
    PCDIR_DEFAULT = $(LIBDIR)/pkgconfig
endif

# ----- install layout ------------------------------------------------------

PREFIX     ?= /usr/local
BINDIR     ?= $(PREFIX)/bin
SBINDIR    ?= $(PREFIX)/sbin
LIBDIR     ?= $(PREFIX)/lib
INCDIR     ?= $(PREFIX)/include
MANDIR     ?= $(PREFIX)/share/man
DOCDIR     ?= $(PREFIX)/share/doc/$(PKG)
PCDIR      ?= $(PCDIR_DEFAULT)

# ----- what we build -------------------------------------------------------

LIB       = $(PKG).a
SOLIB     = $(PKG).$(SOEXT)
SOVER     = $(SOLIB).1

PUBHDR    = include/cx/cx.h
PRIVHDR   = src/cx_priv.h

LIBSRCS   = src/cx_result.c src/cx_io.c src/cx_node.c src/cx_type.c \
            src/cx_complete.c src/cx_help.c src/cx_edit.c src/cx_parse.c \
            src/cx_session.c src/cx_utf8.c
LIBOBJS   = $(LIBSRCS:.c=.o)

CXGEN     = cxgen/cxgen
CXGENSRCS = cxgen/cxgen.c cxgen/cxgen_lex.c cxgen/cxgen_parse.c \
            cxgen/cxgen_check.c cxgen/cxgen_emit_c.c cxgen/cxgen_emit_ds.c \
            cxgen/cxgen_emit_doc.c
CXGENOBJS = $(CXGENSRCS:.c=.o)

SHELLSRCS = shell/cx_shell.c
SHELLOBJS = $(SHELLSRCS:.c=.o)

# The worked example.  An appliance is its grammar plus its handlers plus the
# front end, linked together; there is no one cx-shell binary that serves
# every appliance, because the grammar is compiled in.
EXAMPLE   = examples/thermo/thermo-cli
EXSRCS    = examples/thermo/handlers.c
EXGRAM    = examples/thermo/thermo_grammar

# The second worked example: the same grammar language, against a real
# SQLite database instead of a struct.  Built only when <sqlite3.h> is
# actually available -- see the recipe below -- so a machine without it
# still gets `make all' rather than a failed build over one example.
NOTES_EXAMPLE = examples/notes/notes-cli
NOTESSRCS     = examples/notes/handlers.c
NOTESGRAM     = examples/notes/notes_grammar

TESTSRCS  = tests/t_strerror.c tests/t_io.c tests/t_parse.c tests/t_help.c \
            tests/t_edit.c tests/t_tty.c tests/t_gen.c tests/t_prompt.c \
            tests/t_greedy.c tests/t_sessionvar.c tests/t_dyndefault.c \
            tests/t_initfile.c tests/t_macro.c tests/t_utf8.c \
            tests/t_ask.c tests/t_pager.c tests/t_limits.c \
            tests/t_idle.c tests/t_cxshell.c
TESTS     = $(TESTSRCS:.c=)

# Gates written as shell rather than C, because what they check is a property
# of the built artefacts -- the export set, the absence of process-spawning
# calls -- rather than of any one function.
SHTESTS   = tests/t_symbols.sh tests/t_cxgen.sh tests/t_bothways.sh \
            tests/t_emitdoc.sh tests/t_noexec.sh tests/t_shell.sh \
            tests/t_notes.sh tests/t_fuzz.sh tests/t_install.sh \
            tests/t_cplusplus.sh

# The fuzz harnesses.  Each is built as a plain replay program for the
# suite (tests/t_fuzz.sh) and, by `make fuzz', as a libFuzzer target.
FUZZNAMES = session exec cxgen
FUZZSRCS  = $(FUZZNAMES:%=tests/fuzz/fuzz_%.c) tests/fuzz/replay.c
FUZZSEEDS = $(FUZZNAMES:%=tests/fuzz/seeds_%.txt)
FUZZREPLAY = $(FUZZNAMES:%=tests/fuzz/replay_%)
FUZZBINS  = $(FUZZNAMES:%=tests/fuzz/fuzz_%)
CXGENLIBOBJS = $(filter-out cxgen/cxgen.o,$(CXGENOBJS))

MAN1      = doc/cxgen.1
MAN3      = doc/cx.3
MAN8      = doc/cx-shell.8
MANS      = $(MAN1) $(MAN3) $(MAN8)
MANUALTEX = doc/$(PKG)_manual.tex
MANUAL    = doc/$(PKG)_manual.pdf
THERMOTEX = doc/thermo_chapter.tex

README    = README
PCIN      = $(PKG).pc.in

DISTFILES = Makefile $(README) $(PCIN) $(PUBHDR) $(PRIVHDR) $(LIBSRCS) \
            $(CXGENSRCS) cxgen/cxgen.h \
            $(SHELLSRCS) shell/cx_shell.h \
            $(EXSRCS) examples/thermo/thermo.cx examples/thermo/thermo.init \
            examples/thermo/thermo/handlers.h \
            $(NOTESSRCS) examples/notes/notes.cx \
            examples/notes/notes/handlers.h \
            $(TESTSRCS) tests/t_ways.c tests/t_common.h tests/bench.h \
            tests/t_grammar.h tests/t_gen.cx tests/t_gen_handlers.h \
            tests/t_dyndefault.cx tests/t_dyndefault_handlers.h \
            tests/t_initfile.cx tests/t_initfile_handlers.h \
            tests/t_macro.cx tests/t_macro_handlers.h \
            tests/forbidden.pat $(SHTESTS) $(FUZZSRCS) $(FUZZSEEDS) \
            $(MANS) $(MANUALTEX) $(MANUAL)

.PHONY: all lib cxgen shell examples tests docs man manual test check \
        sanitize-test install install-lib uninstall clean distclean dist \
        fuzz fuzz-run

all: lib cxgen shell examples tests

# ----- library -------------------------------------------------------------

lib: $(LIB) $(SOVER)

$(LIB): $(LIBOBJS)
	$(AR) rcs $@ $(LIBOBJS)
	$(RANLIB) $@

$(SOVER): $(LIBOBJS)
	$(CC) -shared $(SONAME_FLAG)$(SOVER) -o $@ $(LIBOBJS) $(LDFLAGS) \
	    $(LIBS) $(PLATFORM_LIBS)
	rm -f $(SOLIB) && ln -s $(SOVER) $(SOLIB)

src/%.o: src/%.c $(PUBHDR) $(PRIVHDR)
	$(CC) $(CPPFLAGS) $(CFLAGS) $(VIS) -fPIC -c -o $@ $<

# ----- the compiler --------------------------------------------------------

cxgen: $(CXGEN)

$(CXGEN): $(CXGENOBJS)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(CXGENOBJS) $(LIBS)

cxgen/%.o: cxgen/%.c cxgen/cxgen.h $(PUBHDR)
	$(CC) $(CPPFLAGS) -Icxgen $(CFLAGS) -c -o $@ $<

# ----- the front end and the worked example --------------------------------

shell: $(SHELLOBJS)

shell/%.o: shell/%.c shell/cx_shell.h $(PUBHDR)
	$(CC) $(CPPFLAGS) -Ishell $(CFLAGS) -c -o $@ $<

examples: $(EXAMPLE) $(NOTES_EXAMPLE)

$(EXGRAM).c $(EXGRAM).h: examples/thermo/thermo.cx $(CXGEN)
	./$(CXGEN) --emit-c -o $(EXGRAM).c -H $(EXGRAM).h \
	    examples/thermo/thermo.cx

$(EXAMPLE): $(EXSRCS) $(EXGRAM).c $(EXGRAM).h $(SHELLOBJS) $(LIB)
	$(CC) $(CPPFLAGS) -Ishell -Iexamples/thermo $(CFLAGS) $(LDFLAGS) \
	    -o $@ $(EXSRCS) $(EXGRAM).c $(SHELLOBJS) $(LIB) $(LIBS) \
	    $(PLATFORM_LIBS)

# The grammar always builds -- cxgen(1) has no dependency on sqlite3(3) --
# so only the final link is conditional on <sqlite3.h> actually being
# present, exactly as `man' probes for mandoc/groff rather than requiring
# either.  A machine without it gets a skip message here and `make all'
# still succeeds; `make test' skips tests/t_notes.sh the same way t_shell.sh
# already skips when sshd(8) is absent.
$(NOTESGRAM).c $(NOTESGRAM).h: examples/notes/notes.cx $(CXGEN)
	./$(CXGEN) --emit-c -o $(NOTESGRAM).c -H $(NOTESGRAM).h \
	    examples/notes/notes.cx

$(NOTES_EXAMPLE): $(NOTESSRCS) $(NOTESGRAM).c $(NOTESGRAM).h $(SHELLOBJS) $(LIB)
	@if ! echo '#include <sqlite3.h>' | \
	    $(CC) $(CPPFLAGS) -E - >/dev/null 2>&1; then \
	    echo "examples/notes: <sqlite3.h> not found; skipping" \
	         "(install libsqlite3-dev, or the sqlite3 package, to build it)"; \
	    exit 0; \
	fi; \
	$(CC) $(CPPFLAGS) -Ishell -Iexamples/notes $(CFLAGS) $(LDFLAGS) \
	    -o $@ $(NOTESSRCS) $(NOTESGRAM).c $(SHELLOBJS) $(LIB) $(LIBS) \
	    $(PLATFORM_LIBS) -lsqlite3

# ----- generated grammars --------------------------------------------------
#
# tests/t_gen.cx and tests/t_grammar.h describe the same interface, one as a
# description and one as C written by hand.  tests/t_gen drives both through
# an identical session and compares the transcripts, which is what turns the
# whole suite into a test of the compiler.

tests/t_gen_grammar.c tests/t_gen_grammar.h: tests/t_gen.cx $(CXGEN)
	./$(CXGEN) --emit-c -o tests/t_gen_grammar.c \
	    -H tests/t_gen_grammar.h tests/t_gen.cx

tests/t_gen_grammar.o: tests/t_gen_grammar.c tests/t_gen_grammar.h $(PUBHDR)
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) -c -o $@ $<

# tests/t_dyndefault.cx exercises `default $name' through the real compiler:
# lexer, parser, checker and --emit-c, not just the hand-built table
# tests/t_greedy.c and tests/t_prompt.c use for their own features.
tests/t_dyndefault_grammar.c tests/t_dyndefault_grammar.h: \
    tests/t_dyndefault.cx $(CXGEN)
	./$(CXGEN) --emit-c -o tests/t_dyndefault_grammar.c \
	    -H tests/t_dyndefault_grammar.h tests/t_dyndefault.cx

tests/t_dyndefault_grammar.o: tests/t_dyndefault_grammar.c \
    tests/t_dyndefault_grammar.h $(PUBHDR)
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) -c -o $@ $<

# tests/t_initfile.cx exercises cx_session_run_init() against a real
# compiled grammar: a command that changes state, one that always fails,
# one needing confirmation, one above the default privilege, and `quit'.
tests/t_initfile_grammar.c tests/t_initfile_grammar.h: \
    tests/t_initfile.cx $(CXGEN)
	./$(CXGEN) --emit-c -o tests/t_initfile_grammar.c \
	    -H tests/t_initfile_grammar.h tests/t_initfile.cx

tests/t_initfile_grammar.o: tests/t_initfile_grammar.c \
    tests/t_initfile_grammar.h $(PUBHDR)
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) -c -o $@ $<

# tests/t_macro.cx exercises `macro <name> "<line>";' against a real
# compiled grammar: a plain shortcut, one gated by its own privilege, one
# whose body is a typo, and one that expands into itself.
tests/t_macro_grammar.c tests/t_macro_grammar.h: tests/t_macro.cx $(CXGEN)
	./$(CXGEN) --emit-c -o tests/t_macro_grammar.c \
	    -H tests/t_macro_grammar.h tests/t_macro.cx

tests/t_macro_grammar.o: tests/t_macro_grammar.c tests/t_macro_grammar.h \
    $(PUBHDR)
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) -c -o $@ $<

# ----- tests ---------------------------------------------------------------

tests: $(TESTS) $(FUZZREPLAY)

tests/%: tests/%.c $(LIB) $(PUBHDR) $(PRIVHDR) tests/bench.h tests/t_common.h
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) $(LDFLAGS) -o $@ $< $(LIB) \
	    $(LIBS) $(PLATFORM_LIBS)

# t_gen needs the generated tables linked in beside it.
tests/t_gen: tests/t_gen.c tests/t_gen_grammar.o tests/t_grammar.h $(LIB) \
             tests/t_common.h
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) $(LDFLAGS) -o $@ $< \
	    tests/t_gen_grammar.o $(LIB) $(LIBS) $(PLATFORM_LIBS)

# Likewise t_dyndefault, against its own small generated grammar.
tests/t_dyndefault: tests/t_dyndefault.c tests/t_dyndefault_grammar.o \
             tests/t_dyndefault_handlers.h $(LIB) tests/t_common.h
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) $(LDFLAGS) -o $@ $< \
	    tests/t_dyndefault_grammar.o $(LIB) $(LIBS) $(PLATFORM_LIBS)

# Likewise t_initfile and t_macro, each against its own small generated
# grammar.
tests/t_initfile: tests/t_initfile.c tests/t_initfile_grammar.o \
             tests/t_initfile_handlers.h $(LIB) tests/t_common.h
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) $(LDFLAGS) -o $@ $< \
	    tests/t_initfile_grammar.o $(LIB) $(LIBS) $(PLATFORM_LIBS)

tests/t_macro: tests/t_macro.c tests/t_macro_grammar.o \
             tests/t_macro_handlers.h $(LIB) tests/t_common.h
	$(CC) $(CPPFLAGS) -Itests $(CFLAGS) $(LDFLAGS) -o $@ $< \
	    tests/t_macro_grammar.o $(LIB) $(LIBS) $(PLATFORM_LIBS)

# t_cxshell compiles the front end's source straight in, to reach its
# static functions, so it needs shell/ on the include path and is rebuilt
# when that source changes.
tests/t_cxshell: tests/t_cxshell.c shell/cx_shell.c shell/cx_shell.h \
             $(LIB) tests/t_common.h
	$(CC) $(CPPFLAGS) -Itests -Ishell $(CFLAGS) $(LDFLAGS) -o $@ $< \
	    $(LIB) $(LIBS) $(PLATFORM_LIBS)

# ----- fuzz harnesses ------------------------------------------------------
#
# The two session harnesses run the real thermo appliance: its generated
# grammar, and its handlers with main() renamed out of the way.

tests/fuzz/thermo_handlers.o: examples/thermo/handlers.c $(EXGRAM).h \
    shell/cx_shell.h $(PUBHDR)
	$(CC) $(CPPFLAGS) -Ishell -Iexamples/thermo $(CFLAGS) \
	    -Dmain=thermo_main -c -o $@ examples/thermo/handlers.c

tests/fuzz/replay_session tests/fuzz/replay_exec: tests/fuzz/replay_%: \
    tests/fuzz/fuzz_%.c tests/fuzz/replay.c tests/fuzz/thermo_handlers.o \
    $(EXGRAM).c $(EXGRAM).h $(SHELLOBJS) $(LIB)
	$(CC) $(CPPFLAGS) -Iexamples/thermo $(CFLAGS) $(LDFLAGS) -o $@ \
	    tests/fuzz/fuzz_$*.c tests/fuzz/replay.c \
	    tests/fuzz/thermo_handlers.o $(EXGRAM).c $(SHELLOBJS) $(LIB) \
	    $(LIBS) $(PLATFORM_LIBS)

tests/fuzz/replay_cxgen: tests/fuzz/fuzz_cxgen.c tests/fuzz/replay.c \
    $(CXGENLIBOBJS) $(LIB)
	$(CC) $(CPPFLAGS) -Icxgen $(CFLAGS) $(LDFLAGS) -o $@ \
	    tests/fuzz/fuzz_cxgen.c tests/fuzz/replay.c $(CXGENLIBOBJS) \
	    $(LIB) $(LIBS)

# libFuzzer builds: clang only, everything compiled together and
# instrumented, so coverage reaches into the library and the compiler.
# `make fuzz-run FUZZTIME=<seconds>' runs each for that long on every core,
# starting from the seeds, keeping what it learns in tests/fuzz/corpus/ and
# any crash in tests/fuzz/crash-*.  Neither is part of the release.
FUZZCC    ?= clang
FUZZFLAGS ?= -g -O1 -fno-omit-frame-pointer \
             -fsanitize=fuzzer,address,undefined \
             -fno-sanitize-recover=undefined
FUZZTIME  ?= 300
FUZZJOBS  ?= $(shell getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)

fuzz: $(FUZZBINS)

tests/fuzz/fuzz_session tests/fuzz/fuzz_exec: tests/fuzz/fuzz_%: \
    tests/fuzz/fuzz_%.c $(LIBSRCS) $(SHELLSRCS) examples/thermo/handlers.c \
    $(EXGRAM).c $(EXGRAM).h $(PUBHDR) $(PRIVHDR)
	$(FUZZCC) $(CPPFLAGS) -Ishell -Iexamples/thermo $(CSTD) $(FUZZFLAGS) \
	    -Dmain=thermo_main -o $@ tests/fuzz/fuzz_$*.c $(LIBSRCS) \
	    $(SHELLSRCS) examples/thermo/handlers.c $(EXGRAM).c

tests/fuzz/fuzz_cxgen: tests/fuzz/fuzz_cxgen.c $(CXGENSRCS) cxgen/cxgen.h \
    $(LIBSRCS) $(PUBHDR)
	$(FUZZCC) $(CPPFLAGS) -Icxgen $(CSTD) $(FUZZFLAGS) -o $@ \
	    tests/fuzz/fuzz_cxgen.c $(filter-out cxgen/cxgen.c,$(CXGENSRCS)) \
	    $(LIBSRCS)

fuzz-run: fuzz $(FUZZREPLAY)
	@for h in $(FUZZNAMES); do \
	    mkdir -p tests/fuzz/corpus/$$h tests/fuzz/seeddir/$$h || exit 1; \
	    ./tests/fuzz/replay_$$h -w tests/fuzz/seeddir/$$h \
	        -s tests/fuzz/seeds_$$h.txt || exit 1; \
	    echo "== fuzz_$$h: $(FUZZTIME)s on $(FUZZJOBS) jobs"; \
	    ( cd tests/fuzz && ./fuzz_$$h -max_total_time=$(FUZZTIME) \
	        -jobs=$(FUZZJOBS) -workers=$(FUZZJOBS) -close_fd_mask=3 \
	        -max_len=8192 -timeout=10 -rss_limit_mb=4096 \
	        -artifact_prefix=crash-$$h- corpus/$$h seeddir/$$h \
	        > fuzz_$$h.log 2>&1 ); \
	    ls tests/fuzz/crash-$$h-* 2>/dev/null && exit 1; \
	    echo "   no crashes; corpus now `ls tests/fuzz/corpus/$$h | wc -l` inputs"; \
	done

# Each test carries its own internal timeout, but the harness enforces one
# too: a test that blocks on a descriptor must fail the build rather than
# hang it, and `make test' has to stay safe piped into tee(1).
TIMEOUT_CMD := $(shell command -v timeout 2>/dev/null || command -v gtimeout 2>/dev/null)
ifeq ($(TIMEOUT_CMD),)
    RUNTEST = sh -c
else
    RUNTEST = $(TIMEOUT_CMD) 120 sh -c
endif

# The shell gates compile helper programs of their own, so they are given
# the same toolchain and flags the library was built with -- a sanitized
# libcx.a linked with an unsanitized link line fails on the sanitizer's own
# symbols, which looks like a fault in the thing being tested and is not.
test check: lib cxgen shell examples tests
	@CC='$(CC)' CFLAGS='$(CFLAGS)' LDFLAGS='$(LDFLAGS)'; \
	export CC CFLAGS LDFLAGS; \
	fail=0; pass=0; \
	for t in $(TESTS) $(SHTESTS); do \
	    printf '== %s\n' "$$t"; \
	    if $(RUNTEST) "./$$t"; then \
	        pass=`expr $$pass + 1`; \
	    else \
	        echo "** FAILED: $$t"; fail=`expr $$fail + 1`; \
	    fi; \
	done; \
	echo "-- $$pass passed, $$fail failed"; \
	test $$fail -eq 0

# Same suite under ASan/UBSan.  Both gcc and clang support these, and the
# FreeBSD run has historically caught what the Linux run does not.
sanitize-test:
	$(MAKE) clean
	$(MAKE) COPT="-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer" \
	        LDFLAGS="-fsanitize=address,undefined" test
	$(MAKE) clean

# ----- documentation -------------------------------------------------------

docs: man manual

# groff on Linux, mandoc on FreeBSD -- both read mdoc, and neither box has
# the other's renderer.  The .1 sources ship as they are; this target only
# proves they format.
man: $(MANS)
	@for m in $(MANS); do \
	    if command -v mandoc >/dev/null 2>&1; then \
	        mandoc -Tascii $$m > /dev/null || exit 1; \
	    elif command -v groff >/dev/null 2>&1; then \
	        groff -mandoc -Tascii $$m > /dev/null || exit 1; \
	    else \
	        echo "man: neither mandoc nor groff found; not rendering"; \
	    fi; \
	done

manual: $(MANUAL)

# The generated chapter is a build product, exactly like $(EXGRAM).c: it is
# cxgen(1)'s own --emit-tex output for the SAME thermo.cx the shipped binary
# is compiled from, so the reference in chapter 7 cannot describe a command
# the running appliance does not accept.  Not checked into RCS; `make clean'
# removes it.
$(THERMOTEX): examples/thermo/thermo.cx $(CXGEN)
	./$(CXGEN) --emit-tex -o $(THERMOTEX) examples/thermo/thermo.cx

# Three pdflatex passes with makeindex between the first and second: the
# first pass writes the .idx, makeindex sorts it into a .ind, the second
# pass reads that back in, and the third resolves any cross-reference that
# only stabilised once the index existed.  All three run from doc/, which is
# where the .tex, the generated chapter, and pdflatex's own litter all live.
$(MANUAL): $(MANUALTEX) $(THERMOTEX)
	@command -v pdflatex >/dev/null 2>&1 || { \
	    echo "manual: pdflatex not found; install a LaTeX distribution" \
	         "to build $(MANUAL)" >&2; \
	    exit 1; \
	}
	cd doc && pdflatex -interaction=nonstopmode -halt-on-error \
	    $(notdir $(MANUALTEX))
	cd doc && { command -v makeindex >/dev/null 2>&1 && \
	    makeindex $(PKG)_manual.idx || true; }
	cd doc && pdflatex -interaction=nonstopmode -halt-on-error \
	    $(notdir $(MANUALTEX))
	cd doc && pdflatex -interaction=nonstopmode -halt-on-error \
	    $(notdir $(MANUALTEX))

# ----- install -------------------------------------------------------------

# install-lib is the part a program building against libcx needs -- the
# libraries, the header and the pkg-config file -- and is what
# tests/t_install.sh exercises, into a DESTDIR, without needing LaTeX.
install-lib: lib
	$(INSTALL) -d $(DESTDIR)$(LIBDIR) $(DESTDIR)$(INCDIR)/cx \
	              $(DESTDIR)$(PCDIR)
	$(INSTALL) -m 644 $(LIB) $(DESTDIR)$(LIBDIR)
	$(INSTALL) -m 755 $(SOVER) $(DESTDIR)$(LIBDIR)
	cd $(DESTDIR)$(LIBDIR) && rm -f $(SOLIB) && ln -s $(SOVER) $(SOLIB)
	$(INSTALL) -m 644 $(PUBHDR) $(DESTDIR)$(INCDIR)/cx
	sed -e 's|@PREFIX@|$(PREFIX)|' -e 's|@LIBDIR@|$(LIBDIR)|' \
	    -e 's|@INCDIR@|$(INCDIR)|' -e 's|@VERSION@|$(VERSION)|' \
	    $(PCIN) > $(DESTDIR)$(PCDIR)/$(PKG).pc
	chmod 644 $(DESTDIR)$(PCDIR)/$(PKG).pc

install: all manual install-lib
	$(INSTALL) -d $(DESTDIR)$(BINDIR) $(DESTDIR)$(MANDIR)/man1 \
	              $(DESTDIR)$(MANDIR)/man3 $(DESTDIR)$(MANDIR)/man8 \
	              $(DESTDIR)$(DOCDIR)
	$(INSTALL) -m 755 $(CXGEN) $(DESTDIR)$(BINDIR)
	$(INSTALL) -m 644 $(MAN1) $(DESTDIR)$(MANDIR)/man1
	$(INSTALL) -m 644 $(MAN3) $(DESTDIR)$(MANDIR)/man3
	$(INSTALL) -m 644 $(MAN8) $(DESTDIR)$(MANDIR)/man8
	$(INSTALL) -m 644 $(MANUAL) $(DESTDIR)$(DOCDIR)

uninstall:
	rm -f $(DESTDIR)$(LIBDIR)/$(LIB) $(DESTDIR)$(LIBDIR)/$(SOVER) \
	      $(DESTDIR)$(LIBDIR)/$(SOLIB)
	rm -rf $(DESTDIR)$(INCDIR)/cx
	rm -f $(DESTDIR)$(PCDIR)/$(PKG).pc
	rm -f $(DESTDIR)$(BINDIR)/cxgen
	rm -f $(DESTDIR)$(MANDIR)/man1/$(notdir $(MAN1))
	rm -f $(DESTDIR)$(MANDIR)/man3/$(notdir $(MAN3))
	rm -f $(DESTDIR)$(MANDIR)/man8/$(notdir $(MAN8))
	rm -rf $(DESTDIR)$(DOCDIR)

# ----- housekeeping --------------------------------------------------------

clean:
	rm -f $(LIBOBJS) $(LIB) $(SOLIB) $(SOVER) $(TESTS) $(CXGEN) $(EXAMPLE) \
	      $(NOTES_EXAMPLE)
	rm -f src/*.o tests/*.o cxgen/*.o shell/*.o examples/thermo/*.o \
	      examples/notes/*.o
	rm -f tests/t_gen_grammar.c tests/t_gen_grammar.h
	rm -f tests/t_dyndefault_grammar.c tests/t_dyndefault_grammar.h
	rm -f tests/t_initfile_grammar.c tests/t_initfile_grammar.h
	rm -f tests/t_macro_grammar.c tests/t_macro_grammar.h
	rm -f $(FUZZREPLAY) $(FUZZBINS) tests/fuzz/*.o
	rm -f $(EXGRAM).c $(EXGRAM).h
	rm -f $(NOTESGRAM).c $(NOTESGRAM).h
	rm -f $(THERMOTEX)
	rm -f *.aux *.log *.toc *.out *.idx *.ilg *.ind
	rm -f doc/*.aux doc/*.log doc/*.toc doc/*.out doc/*.idx doc/*.ilg \
	      doc/*.ind doc/pdflatex.log

distclean: clean
	rm -f $(MANUAL) $(PKG)-*.tar.gz
	rm -rf tests/fuzz/corpus tests/fuzz/seeddir tests/fuzz/crash-* \
	       tests/fuzz/fuzz_*.log tests/fuzz/fuzz-*.log
	rm -rf $(DISTDIR)

# ----- release ---------------------------------------------------------------
#
# Builds the manual first -- the tarball ships the PDF so a reader without
# LaTeX still has documentation -- then copies DISTFILES into a directory
# named for the release and tars that.  Verify by unpacking the actual
# .tar.gz into an empty directory on both platforms and running
# `make && make test'; that is the only check of what was actually shipped,
# as opposed to what the working tree happens to contain right now.
dist: $(MANUAL)
	rm -rf $(DISTDIR) $(DISTDIR).tar.gz
	mkdir -p $(DISTDIR)
	for f in $(DISTFILES); do \
	    mkdir -p $(DISTDIR)/`dirname $$f`; \
	    cp $$f $(DISTDIR)/$$f || exit 1; \
	done
	tar czf $(DISTDIR).tar.gz $(DISTDIR)
	rm -rf $(DISTDIR)
	@echo "release: $(DISTDIR).tar.gz"
	@echo "verify with: tar xzf $(DISTDIR).tar.gz && cd $(DISTDIR) && make && make test"
