# Build folder
BUILD_DIR = build

# Source files
SOURCES := \
  src/main.c

# Output target name
OUTPUT := Test_SDL3

# Compiler and flags
CC = gcc
CCFLAGS = --std=c17 --pedantic -O0 -g $(shell pkg-config --cflags sdl3) \
	-Wall -Wno-missing-braces -Wextra -Wno-missing-field-initializers \
    -Wformat=2 -Wswitch-default -Wswitch-enum -Wcast-align \
    -Wpointer-arith -Wbad-function-cast -Wstrict-overflow=5 \
    -Wstrict-prototypes -Winline -Wundef -Wnested-externs \
    -Wcast-qual -Wshadow -Wunreachable-code -Wlogical-op \
    -Wfloat-equal -Wstrict-aliasing=2 -Wredundant-decls \
    -Wold-style-definition

LDFLAGS = $(shell pkg-config --libs sdl3)

# Include directories
INCLUDE_DIRS =

# Change output location
OUTPUT := $(BUILD_DIR)/$(OUTPUT)

# Deduce objects
OBJECTS = $(SOURCES:%.c=$(BUILD_DIR)/%.o)

# Verbose mode
ifeq ($(VERBOSE), 1)
Q :=
else
Q := @
endif

# Colors
GREEN  := \033[32m
YELLOW := \033[33m
RESET  := \033[m

# Current file nb to process
CURRENT_FILE := 0

# Default targets
all: count_build build_dir end

# Create build directory
build_dir:
	$(Q)mkdir -p $(dir $(OBJECTS))

# Link target
$(OUTPUT): $(OBJECTS)
	@echo -e "[100%] $(YELLOW)Linking $(OUTPUT)$(RESET)"
	$(Q)$(CC) $(LDFLAGS) -o $@ $(OBJECTS)

# Build .o files from .c
$(BUILD_DIR)/%.o: %.c
	$(eval CURRENT_FILE := $(shell echo $$(($(CURRENT_FILE)+1))))
	$(eval PERCENTAGE := $(shell echo $$(($(CURRENT_FILE)*100/$(TOTAL_FILES)))))
	@echo -e "[$(PERCENTAGE)%] $(GREEN)Building C object $@$(RESET)"
	$(Q)$(CC) $(CCFLAGS) $(INCLUDE_DIRS:%=-I%) -MMD -MP -c $< -o $@

# Source files dependencies
-include $(OBJECTS:.o=.d)

count_build:
	$(eval export TOTAL_FILES := $(shell echo $$(($$(make -n $(OBJECTS) 2>/dev/null | grep -c "Building") + 1))))

# Print ending message
end: $(OUTPUT)
	@echo "Built target $(OUTPUT)"

# Clean
.PHONY: clean
clean:
	$(Q)rm -rf $(BUILD_DIR)

# Run executable
.PHONY: run
run: all
	$(Q)./$(OUTPUT)
