# ---------------------------------------------------------------------------
# libcpmfs -- CP/M and TurboDOS disk-image file systems
#
# $Id: Makefile,v 1.4 2026/12/03 22:22:54 rec Exp $
#
# Author:  Robert Cousins
# Purpose: Build the library, the cpmfs(1) tool, the cpmfs-mount(1) FUSE
#          tool (when libfuse3 is present), the examples, the test
#          programs, the man pages and the LaTeX manual, and roll a
#          release tarball.
#
# Copyright (c) 2026, Robert Cousins.  3-clause BSD; the full text is in
# cpmfs.h.
#
# The release contract: the user downloads libcpmfs-<version>.tar.gz,
# unpacks it in an empty directory, and types
#
#       make ; sudo make install
#
# There is no configure script.  Platform differences are handled by the
# uname-driven block below, and the one optional dependency -- libfuse3,
# for cpmfs-mount only -- by asking pkg-config whether it is there.  The
# library itself needs nothing but libc.
#
# Versions:
#   1.0.0  2026-12-02  Robert Cousins  Initial version.
#   1.0.0  2026-12-03  Robert Cousins  tests/t_floppy and
#          examples/turbodos.diskdefs; tests/t_bytes.
# ---------------------------------------------------------------------------

PKG      = libcpmfs
VERSION  = 1.0.0
DISTDIR  = $(PKG)-$(VERSION)

# ----- toolchain -----------------------------------------------------------
# -std=c2x is the newest standard accepted by BOTH gcc 13 (Linux) and
# clang 19 (FreeBSD); gcc 13 rejects -std=c23.  Each .c also defines
# _POSIX_C_SOURCE 200809L before its includes, because c2x is strict ISO.

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

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

UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
    PLATFORM_LIBS =
    UNMOUNT       = fusermount3 -u
endif
ifeq ($(UNAME_S),FreeBSD)
    PLATFORM_LIBS =
    UNMOUNT       = umount
endif
ifeq ($(UNAME_S),Darwin)
    PLATFORM_LIBS =
    UNMOUNT       = umount
endif

# libfuse3, for cpmfs-mount only.
HAVE_FUSE  := $(shell $(PKGCONF) --exists fuse3 2>/dev/null && echo yes)
FUSE_CFLAGS = $(shell $(PKGCONF) --cflags fuse3 2>/dev/null)
FUSE_LIBS   = $(shell $(PKGCONF) --libs fuse3 2>/dev/null)

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

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

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

LIB      = $(PKG).a
HDRS     = cpmfs.h cpm_priv.h
LIBSRCS  = cpm_err.c cpm_geom.c cpm_diskdefs.c cpm_io.c cpm_dir.c \
           cpm_file.c cpm_fsck.c cpm_mkfs.c cpm_imd.c
LIBOBJS  = $(LIBSRCS:.c=.o)

TOOL     = cpmfs
TOOLHDRS = cpmfs_tool.h
TOOLSRCS = cpmfs_main.c cpmfs_util.c
TOOLOBJS = $(TOOLSRCS:.c=.o)

MOUNT    = cpmfs-mount
MOUNTSRC = cpmfs_mount.c
ifeq ($(HAVE_FUSE),yes)
MOUNTBIN = $(MOUNT)
else
MOUNTBIN =
endif

EXAMPLES = examples/listdisk examples/textcopy examples/mkdisk
TESTS    = tests/t_err tests/t_geom tests/t_diskdefs tests/t_io tests/t_dir \
           tests/t_file tests/t_fsck tests/t_mkfs tests/t_imd tests/t_td \
           tests/t_floppy tests/t_bytes tests/t_prop
SHTESTS  = tests/t_tool.sh tests/t_fuzz.sh tests/t_cpmtools.sh \
           tests/t_mount.sh
REPLAYS  = tests/replay_image tests/replay_diskdefs tests/replay_imd
FUZZERS  = tests/fuzz_image tests/fuzz_diskdefs tests/fuzz_imd
FUZZNAMES = image diskdefs imd
MANS3    = cpmfs.3
MANS1    = cpmfs.1 cpmfs-mount.1
MANUAL   = $(PKG)_manual.pdf

DATA     = examples/sample.diskdefs examples/turbodos.diskdefs \
           examples/mkdata.py \
           examples/data/memo.txt examples/data/parts.dat \
           examples/data/sieve.bas examples/data/hi.com

DISTFILES = Makefile README LICENSE CHANGELOG PLAN.md $(HDRS) $(LIBSRCS) \
            $(TOOLHDRS) $(TOOLSRCS) $(MOUNTSRC) $(MANS3) $(MANS1) \
            $(PKG)_manual.tex $(MANUAL) manual_figs.tex \
            $(EXAMPLES:=.c) $(DATA) \
            $(TESTS:=.c) $(SHTESTS) tests/bench.h tests/t_util.h \
            tests/t_ref.h tests/t_dst.h tests/imdwrite.py \
            tests/mount_stress.py \
            tests/fuzz_image.c tests/fuzz_diskdefs.c tests/fuzz_imd.c \
            tests/fuzz_replay.c tests/seeds_image.txt \
            tests/seeds_diskdefs.txt tests/seeds_imd.txt \
            doc/mkexamples.sh \
            $(filter-out doc/ex/td_log.txt doc/ex/td_run.txt \
                doc/ex/td_lock2.%,$(wildcard doc/ex/*))

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

all: lib tool mount examples tests

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

lib: $(LIB)

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

%.o: %.c $(HDRS) $(TOOLHDRS)
	$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

# ----- the tools -----------------------------------------------------------

tool: $(TOOL)

$(TOOL): $(TOOLOBJS) $(LIB)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(TOOLOBJS) $(LIB) $(LIBS) $(PLATFORM_LIBS)

# cpmfs-mount is built only where pkg-config finds fuse3; everything else
# (make, make test, make dist) works without it.
mount: $(MOUNTBIN)
ifneq ($(HAVE_FUSE),yes)
	@echo "cpmfs-mount: not built (pkg-config finds no fuse3; install libfuse3's development files)"
endif

$(MOUNT): $(MOUNTSRC) cpmfs_util.o $(LIB) $(HDRS) $(TOOLHDRS)
	$(CC) $(CPPFLAGS) $(FUSE_CFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $(MOUNTSRC) \
	    cpmfs_util.o $(LIB) $(FUSE_LIBS) $(LIBS) $(PLATFORM_LIBS)

# ----- examples and tests --------------------------------------------------

examples: $(EXAMPLES)
tests: $(TESTS) $(REPLAYS) $(TOOL)

examples/%: examples/%.c $(LIB)
	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $< $(LIB) $(LIBS) $(PLATFORM_LIBS)

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

# The fuzz harnesses built with the ordinary compiler and fuzz_replay.c's
# main(), so that make test (and make sanitize-test) runs every seed.
tests/replay_%: tests/fuzz_%.c tests/fuzz_replay.c $(LIB)
	$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ tests/fuzz_$*.c \
	    tests/fuzz_replay.c $(LIB) $(LIBS) $(PLATFORM_LIBS)

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

docs: man manual

# Rendered man pages are a convenience; the sources ship as-is.  groff on
# Linux, mandoc on FreeBSD -- both read mdoc.
man: $(MANS1) $(MANS3)
	@for m in $(MANS1) $(MANS3); do \
	    if command -v groff >/dev/null 2>&1; then \
	        groff -mandoc -Tps $$m > $$m.ps || exit 1; \
	    elif command -v mandoc >/dev/null 2>&1; then \
	        mandoc -Tps $$m > $$m.ps || exit 1; \
	    fi; \
	done

manual: $(MANUAL)

# The manual shows real output: doc/mkexamples.sh runs the built programs
# and saves what they print in doc/ex/, which the manual includes.
$(MANUAL): $(PKG)_manual.tex manual_figs.tex doc/mkexamples.sh $(TOOL) \
           $(EXAMPLES) $(DATA)
	sh doc/mkexamples.sh
	pdflatex -interaction=batchmode $(PKG)_manual.tex >/dev/null || \
	    { tail -40 $(PKG)_manual.log; exit 1; }
	makeindex $(PKG)_manual.idx >/dev/null 2>&1 || true
	pdflatex -interaction=batchmode $(PKG)_manual.tex >/dev/null
	pdflatex -interaction=batchmode $(PKG)_manual.tex >/dev/null

# ----- testing -------------------------------------------------------------
# Shell tests print SKIPPED (and exit 77) when what they need is absent:
# cpmtools for t_cpmtools.sh, a working FUSE for t_mount.sh.  A skip is
# reported, never counted as a pass.

test check: tests mount
	@fail=0; skip=0; \
	for t in $(TESTS); do \
	    echo "== $$t"; ./$$t || fail=1; \
	done; \
	for t in $(SHTESTS); do \
	    echo "== $$t"; UNMOUNT="$(UNMOUNT)" sh $$t ./$(TOOL) ./$(MOUNT); rc=$$?; \
	    if [ $$rc -eq 77 ]; then skip=$$((skip + 1)); \
	    elif [ $$rc -ne 0 ]; then fail=1; fi; \
	done; \
	if [ $$fail -eq 0 ]; then echo "ALL TESTS PASSED ($$skip shell tests skipped)"; \
	else echo "SOME TESTS FAILED"; fi; \
	exit $$fail

# Run the same suite under ASan/UBSan.  Both gcc and clang support these.
sanitize-test:
	$(MAKE) clean
	$(MAKE) COPT="-O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all" \
	        LDFLAGS="-fsanitize=address,undefined" test
	$(MAKE) clean

# libFuzzer harnesses for the ways outside bytes get in.  clang with
# libFuzzer (FreeBSD's base clang; on Ubuntu, libclang-rt-18-dev).
FUZZFLAGS = -g -O1 -fno-omit-frame-pointer -fsanitize=fuzzer,address,undefined \
            -fno-sanitize-recover=undefined
FUZZTIME ?= 1200
FUZZJOBS ?= 4

fuzz: $(FUZZERS)

tests/fuzz_%: tests/fuzz_%.c $(LIBSRCS) $(HDRS)
	clang $(CSTD) $(FUZZFLAGS) -I. -o $@ tests/fuzz_$*.c $(LIBSRCS)

# A campaign: each harness for FUZZTIME seconds on FUZZJOBS cores, starting
# from its seeds and the corpus a previous campaign left.
fuzz-run: fuzz $(REPLAYS)
	@for h in $(FUZZNAMES); do \
	    mkdir -p tests/corpus/$$h tests/seeddir/$$h; \
	    ./tests/replay_$$h -w tests/seeddir/$$h -s tests/seeds_$$h.txt; \
	    ./tests/fuzz_$$h -max_total_time=$(FUZZTIME) -jobs=$(FUZZJOBS) \
	        -workers=$(FUZZJOBS) -close_fd_mask=3 -max_len=65536 \
	        -timeout=10 -rss_limit_mb=4096 -artifact_prefix=crash-$$h- \
	        tests/corpus/$$h tests/seeddir/$$h || exit 1; \
	done

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

install: all
	$(INSTALL) -d $(DESTDIR)$(BINDIR) $(DESTDIR)$(LIBDIR) \
	              $(DESTDIR)$(INCDIR) $(DESTDIR)$(MANDIR)/man1 \
	              $(DESTDIR)$(MANDIR)/man3 $(DESTDIR)$(DOCDIR)
	$(INSTALL) -m 755 $(TOOL) $(DESTDIR)$(BINDIR)
	@if [ -f $(MOUNT) ]; then \
	    echo "$(INSTALL) -m 755 $(MOUNT) $(DESTDIR)$(BINDIR)"; \
	    $(INSTALL) -m 755 $(MOUNT) $(DESTDIR)$(BINDIR); fi
	$(INSTALL) -m 644 $(LIB) $(DESTDIR)$(LIBDIR)
	$(INSTALL) -m 644 cpmfs.h $(DESTDIR)$(INCDIR)
	$(INSTALL) -m 644 $(MANS1) $(DESTDIR)$(MANDIR)/man1
	$(INSTALL) -m 644 $(MANS3) $(DESTDIR)$(MANDIR)/man3
	@if [ -f $(MANUAL) ]; then \
	    $(INSTALL) -m 644 $(MANUAL) $(DESTDIR)$(DOCDIR); fi
	$(INSTALL) -m 644 $(DATA) $(DESTDIR)$(DOCDIR)

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/$(TOOL) $(DESTDIR)$(BINDIR)/$(MOUNT)
	rm -f $(DESTDIR)$(LIBDIR)/$(LIB)
	rm -f $(DESTDIR)$(INCDIR)/cpmfs.h
	for m in $(MANS1); do rm -f $(DESTDIR)$(MANDIR)/man1/$$m; done
	rm -f $(DESTDIR)$(MANDIR)/man3/$(MANS3)
	rm -rf $(DESTDIR)$(DOCDIR)

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

clean:
	rm -f $(LIBOBJS) $(TOOLOBJS) $(LIB) $(TOOL) $(MOUNT) $(EXAMPLES) \
	      $(TESTS) $(REPLAYS) $(FUZZERS) *.o *.ps fuzz-*.log
	rm -f *.aux *.log *.toc *.out *.idx *.ilg *.ind *.lof *.lot
	rm -rf tests/tmp

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

# ----- release -------------------------------------------------------------
# Builds the manual first: the tarball ships the PDF so that a user without
# LaTeX can still read the documentation.

dist: $(MANUAL)
	rm -rf $(DISTDIR) $(DISTDIR).tar.gz
	mkdir -p $(DISTDIR)
	for f in $(DISTFILES); do \
	    mkdir -p $(DISTDIR)/`dirname $$f`; \
	    cp -p $$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"
