CC           = clang
BUILD_TYPE   = debug
CFLAGS       = -Wall -Wextra -Werror -pedantic
LIBFLAGS     = -fPIC -shared
KERNEL       = $(shell uname -s)
MACHINE      = $(shell uname -m)
PLATFORM     = $(KERNEL)_$(MACHINE)
TEST_INCLUDE = -Isrc $(shell find tests -type d | xargs -I{} echo -n "-I{} ")
TEST_SRC     = src/wapp.c $(shell find tests -type f -name "*.c" | xargs -I{} echo -n "{} ")
BUILD_DIR    = libwapp-build/$(PLATFORM)-$(BUILD_TYPE)
LIB_OUT      = $(BUILD_DIR)/libwapp.so
TEST_OUT     = $(BUILD_DIR)/wapptest

ifeq ($(BUILD_TYPE),debug)
	CFLAGS += -g -fsanitize=address,undefined
else ifeq ($(BUILD_TYPE),release)
	CFLAGS += -O3
else
	$(error Invalid BUILD type '$(BUILD_TYPE)'. Use 'debug' or 'release')
endif

ifeq ($(CC),gcc)
  # Used to disable the "ASan runtime does not come first in initial library list" error when compiling with gcc
  export ASAN_OPTIONS=verify_asan_link_order=0
endif

.PHONY: all clean builddir codegen build-test run-test build-lib full prng testing uuid core

all: clean builddir codegen run-test full

clean:
	@rm -rf $(BUILD_DIR)

builddir:
	@mkdir -p $(BUILD_DIR)

codegen:
	python3 -m codegen

build-test:
	$(CC) $(CFLAGS) $(TEST_INCLUDE) $(TEST_SRC) -o $(TEST_OUT)

run-test: build-test
	@$(TEST_OUT)
	@rm $(TEST_OUT)

build-lib:
	$(CC) $(CFLAGS) $(LIBFLAGS) $(LIB_SRC) -o $(LIB_OUT)

full: LIB_SRC = src/wapp.c
full: build-lib

prng: LIB_SRC = src/prng/wapp_prng.c
prng: build-lib

testing: LIB_SRC = src/testing/wapp_testing.c
testing: build-lib

uuid: LIB_SRC = src/uuid/wapp_uuid.c
uuid: build-lib

core: LIB_SRC = src/core/wapp_core.c
core: build-lib