# Record Manager — build, test, and verification targets.
#
# Best-practice references:
#   - GNU Make automatic prerequisites: https://www.gnu.org/software/make/manual/html_node/Automatic-Prerequisites.html
#   - GCC instrumentation (sanitizers):  https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html

CC      ?= cc
CFLAGS  ?= -std=c17 -Wall -Wextra -Wpedantic -Werror -g
CPPFLAGS += -Iinclude -MMD -MP
LDLIBS   ?=

SRC := $(wildcard src/*.c)
OBJ := $(SRC:src/%.c=build/%.o)
DEP := $(OBJ:.o=.d)
BIN := build/recman

all: $(BIN)

$(BIN): $(OBJ)
	$(CC) $(CFLAGS) $^ -o $@ $(LDLIBS)

build/%.o: src/%.c | build
	$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@

build:
	mkdir -p build

test: $(BIN)
	sh tests/smoke.sh $(BIN)

# ASan + UBSan — zero tolerance for memory and undefined-behavior errors.
sanitize:
	$(CC) $(CFLAGS) -fsanitize=address,undefined $(CPPFLAGS) $(SRC) -o build/recman_asan $(LDLIBS)
	sh tests/smoke.sh build/recman_asan

valgrind: $(BIN)
	@command -v valgrind >/dev/null 2>&1 || { echo "error: valgrind not installed (see toolchain setup)"; exit 1; }
	printf 'add Ada ada@x.io 555-0100\nlist\nquit\n' | valgrind --leak-check=full --show-leak-kinds=all --error-exitcode=1 $(BIN) >/dev/null

clean:
	rm -rf build

-include $(DEP)

.PHONY: all test sanitize valgrind clean
