.POSIX:
CC           = c99
CFLAGS       = -std=c99 -Wall -Wextra -Wpedantic -fPIC -g -O3
LDFLAGS      = -Wl,-rpath,$$LIBRARY_PATH
LDLIBS       =
PREFIX       = /usr/local
MANPREFIX    = $(PREFIX)/share/man
DATE         = 1970-01-01
MAJOR        = 0
MINOR        = 1
PATCH        = 0
VERSION      = $(MAJOR).$(MINOR).$(PATCH)
NAME         = __PROJECT__
MAILING_LIST = __MAILING_LIST__

headers = \
	src/f.h

sources = \
	src/f.c

binaries = \
	f

manpages = \
	doc/f.1


objects = $(sources:.c=.o)

.SUFFIXES: .c .o

.c.o:
	$(CC) -c $(CFLAGS) $(LDFLAGS) -o $@ $<

libname    = lib$(NAME)
liba       = $(libname).a
libso      = $(libname).so
libso-real = $(libso).$(MAJOR).$(MINOR).$(PATCH)
soaliases  = $(libso).$(MAJOR).$(MINOR) $(libso).$(MAJOR) $(libso)

all: $(liba) $(libso-real) run-tests

$(liba): $(headers) $(objects)
	ar rcsv $@-t $(objects)
	ranlib $@-t
	mv $@-t $@

$(libso-real): $(headers) $(objects)
	$(CC) $(CFLAGS) $(LDFLAGS) -shared -Wl,-soname,$(libso).$(MAJOR) -o $@ $(objects)

$(soaliases): $(libso-real)
	ln -sf $? $@

run-tests: $(headers) $(sources) tests/tests.c
	$(CC) $(CFLAGS) $(LDFLAGS) -DTEST            -o $@ tests/tests.c $(sources) $(LDLIBS)

fallible-tests: $(headers) $(sources) tests/tests.c
	$(CC) $(CFLAGS) $(LDFLAGS) -DTEST -DFALLIBLE -o $@ tests/tests.c $(sources) $(LDLIBS) -lfallible

check: run-tests
	./run-tests

dev-check: all check fallible-tests
	valgrind `fallible-check --valgrind-flags` ./run-tests
	fallible-check ./fallible-tests
	sh aux/assert-shellcheck.sh
	sh aux/workflow/assert-todos.sh
	sh aux/workflow/assert-changelog.sh $(NAME)

do_subst = sed \
	-e 's:[@]VERSION[@]:$(VERSION):g' \
	-e 's:[@]DATE[@]:$(DATE):g'

install: all $(soaliases)
	for h in $(headers); do install -m 644 -D $$h $(DESTDIR)$(PREFIX)/include/`basename $$h`; done
	for f in $(liba) $(libso-real); do install -m 755 -D $$f $(DESTDIR)$(PREFIX)/lib/$$f; done
	for a in $(soaliases); do mv $$a $(DESTDIR)$(PREFIX)/lib/; done
	for b in $(binaries); do install -m 755 -D $$b $(DESTDIR)$(PREFIX)/bin/$$b; done
	for m in $(manpages); do \
		n=$${m##*.}; \
		mkdir -p $(DESTDIR)$(MANPREFIX)/man$$n; \
		$(do_subst) < $$m | gzip > $(DESTDIR)$(MANPREFIX)/man$$n/`basename $$m`.gz; \
	done

uninstall:
	for h in $(headers); do rm -f $(DESTDIR)$(PREFIX)/include/`basename $$h`; done
	for l in $(liba) $(libso-real) $(soaliases); do rm -f $(DESTDIR)$(PREFIX)/lib/$$l; done
	for m in $(manpages); do rm -f $(DESTDIR)$(MANPREFIX)/man$${m##*.}/`basename $$m`.gz; done

clean:
	rm -rf public/ $(objects) $(liba) $(libso-real) $(soaliases) run-tests fallible* vgcore*

dist: clean public dev-check
	sh aux/workflow/dist.sh $(DATE) $(VERSION) $(NAME)

public: README.md TODOs.md CHANGELOG.md
	sh aux/workflow/public.sh __PROJECT_UC__ $(NAME) $(MAILING_LIST)

.PHONY: all clean check dev-check dist install uninstall
