# libkyrka tests Makefile

CC?=cc
LIBKYRKA?=../host-build/usr/local/

OBJDIR?=obj
LIB=$(OBJDIR)/libtest.a

CFLAGS+=-std=c99 -pedantic -Wall -Werror -Wstrict-prototypes
CFLAGS+=-Wmissing-prototypes -Wmissing-declarations -Wshadow
CFLAGS+=-Wpointer-arith -Wcast-qual -Wsign-compare -O2 -fPIC
CFLAGS+=-fstack-protector-all -Wtype-limits -fno-common
CFLAGS+=-I$(LIBKYRKA)/include/libkyrka -I../nyfe/include -I.
CFLAGS+=-g

SRC=	framework.c

TESTS=	$(OBJDIR)/test-api \
	$(OBJDIR)/test-vicar \
	$(OBJDIR)/test-packet \
	$(OBJDIR)/test-kdf \
	$(OBJDIR)/test-offer \
	$(OBJDIR)/test-shroud \
	$(OBJDIR)/test-cathedral \
	$(OBJDIR)/test-key \
	$(OBJDIR)/test-cipher \
	$(OBJDIR)/test-asymmetry \
	$(OBJDIR)/test-mlkem \
	$(OBJDIR)/test-purgatory \
	$(OBJDIR)/test-heaven
OBJS=	$(SRC:%.c=$(OBJDIR)/%.o)

OSNAME=$(shell uname -s | sed -e 's/[-_].*//g' | tr A-Z a-z)

ifeq ("$(OSNAME)", "linux")
	CFLAGS+=-D_GNU_SOURCE=1 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2
endif

# XXX ideally should be tied to the mk stuff in libkyrka
# so tests can be run with all type of builds.
CFLAGS+=	$(shell pkg-config libsodium --cflags)
LDFLAGS+=	$(LIBKYRKA)/lib/libkyrka.a $(LIB)
LDFLAGS+=	$(shell pkg-config libsodium --libs)

# XXX library build should be done with sanitizers.
LDFLAGS+=	-fsanitize=address,undefined -fprofile-arcs

all: test

test: $(TESTS)
	@status=0; \
	for t in $(TESTS); do \
		./$$t || status=1; \
	done; \
	exit $$status

$(LIB): $(OBJS) $(OBJDIR)
	$(AR) rcs $(LIB) $(OBJS)

$(OBJDIR)/test-%: $(LIB) tests/%.c
	$(CC) $(CFLAGS) tests/$*.c $(LDFLAGS) -o $@

$(OBJDIR):
	mkdir -p $(OBJDIR)

$(OBJDIR)/%.o: %.c
	@mkdir -p $(shell dirname $@)
	$(CC) $(CFLAGS) -c $< -o $@

coverage: coverage_html

coverage_html: coverage.info
	genhtml -o coverage_html coverage.info

coverage.info: $(TESTS)
	for t in $(TESTS); do ./$$t; done
	lcov -d ../obj-host -c -o coverage.info

clean:
	rm -rf $(LIB)
	rm -rf $(OBJDIR)
	rm -rf coverage*

.PHONY: all clean test
