# Makefile at project root

CC       := gcc
CFLAGS   := -O3 -fPIC -Wall -Wextra
LDFLAGS  := -shared

SRCDIR   := engine/src
INCDIR   := engine/include
BUILDDIR := build
LIBNAME  := libchess

UNAME_S  := $(shell uname -s)
ifeq ($(UNAME_S),Darwin)
  SOEXT := dylib
else
  SOEXT := so
endif

SRC := $(wildcard $(SRCDIR)/*.c)
OBJ := $(patsubst $(SRCDIR)/%.c,$(BUILDDIR)/%.o,$(SRC))
LIB := $(BUILDDIR)/$(LIBNAME).$(SOEXT)

.PHONY: all clean clean-pycache test

all: $(LIB)

$(BUILDDIR):
	@mkdir -p $(BUILDDIR)

# compile each .c into build/*.o
$(BUILDDIR)/%.o: $(SRCDIR)/%.c | $(BUILDDIR)
	$(CC) $(CFLAGS) -I$(INCDIR) -c $< -o $@

# link shared library
$(LIB): $(OBJ)
	$(CC) $(LDFLAGS) -o $@ $^

clean:
	@echo "Cleaning Python caches..."
	@find . -type d -name "__pycache__"  -exec rm -rf {} +
	@find . -type d -name ".pytest_cache" -exec rm -rf {} +
	@find . -type f \( -name "*.pyc" -o -name "*.pyo" \) -delete

# run Python unit tests
test: all
	python3 -m unittest -v && $(MAKE) clean
