# Makefile for building the application
# Use:
# make              - compiles both release and test binaries
# make release      - compiles and runs the release binary
# make test         - compiles and runs the test binary
# make clean        - deletes all binaries in build/bin
# make cleaner      - deltes the whole build directory

# Compiler
CC = clang
CFLAGS = -Wall -Wextra -Werror -I$(ENCLAVE_DIR) -I$(APP_DIR)
LDFLAGS = 

# Directories
SRC_DIR = src
LIB_DIR = lib
TEST_DIR = test
APP_DIR = $(SRC_DIR)/app
ENCLAVE_DIR = $(SRC_DIR)/enclave
BUILD_DIR = build
OBJ_DIR = $(BUILD_DIR)/obj
BIN_DIR = $(BUILD_DIR)/bin

# Source files
LIB_SRCS = $(wildcard $(LIB_DIR)/*.c)
APP_SRCS = $(wildcard $(APP_DIR)/*.c) $(wildcard $(ENCLAVE_DIR)/*.c)
TEST_SRCS = $(wildcard $(TEST_DIR)/*.c)

# Object files
LIB_OBJS = $(LIB_SRCS:$(LIB_DIR)/%.c=$(OBJ_DIR)/lib/%.o)
APP_OBJS = $(APP_SRCS:$(SRC_DIR)/%.c=$(OBJ_DIR)/src/%.o)
TEST_OBJS = $(TEST_SRCS:$(TEST_DIR)/%.c=$(OBJ_DIR)/test/%.o)

# Binaries
RELEASE_BIN = $(BIN_DIR)/release
TEST_BIN = $(BIN_DIR)/test

$(RELEASE_BIN): $(LIB_OBJS) $(APP_OBJS)
	@mkdir -p $(BIN_DIR)
	@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

$(TEST_BIN): $(LIB_OBJS) $(TEST_OBJS)
	@mkdir -p $(BIN_DIR)
	@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/lib/%.o: $(LIB_DIR)/%.c
	@mkdir -p $(dir $@)
	@$(CC) $(CFLAGS) -c -o $@ $<

$(OBJ_DIR)/src/%.o: $(SRC_DIR)/%.c
	@mkdir -p $(dir $@)
	@$(CC) $(CFLAGS) -c -o $@ $<

$(OBJ_DIR)/test/%.o: $(TEST_DIR)/%.c
	@mkdir -p $(dir $@)
	@$(CC) $(CFLAGS) -c -o $@ $<

# Targets
.PHONY: all clean release test

all: release test

release: $(RELEASE_BIN) run_release

run_release:
	@echo "RUNNING RELEASE"
	@./$(RELEASE_BIN)

test: $(TEST_BIN) run_test

run_test: 
	@echo "RUNNING TESTS"
	@./$(TEST_BIN)

clean:
	@echo "Deleting binaries"
	@rm -rf $(BIN_DIR)

cleaner:
	@echo "Deleting builds"
	@rm -rf $(BUILD_DIR)
