# Compiler and flags
CC = x86_64-w64-mingw32-gcc
LDFLAGS = -lws2_32 -liphlpapi -static
INCLUDE_DIR =
SRC_DIR = .
OBJ_DIR = obj
BIN_DIR = .
EXEC = $(BIN_DIR)/beacon.exe

# Define default flags
CFLAGS = -flto -Os -DTESTING_BUILD

# Define feature flags
USE_SCHANNEL = FALSE
USE_HTTP = FALSE

# Basic source files (always included)
SRC_FILES = \
	beacon.c \

# Add transport implementation based on USE_SCHANNEL
ifeq ($(USE_SCHANNEL),TRUE)
	CFLAGS += -DUSE_SCHANNEL=TRUE
	LDFLAGS += -lsecur32
	SRC_FILES += transport_schannel.c
else ifeq ($(USE_HTTP),TRUE)
	CFLAGS += -DUSE_HTTP=TRUE
	LDFLAGS += -lwinhttp
	SRC_FILES += transport_http.c
else
	SRC_FILES += transport_tcp.c
endif

# Generate source file paths
SOURCES = $(addprefix $(SRC_DIR)/, $(SRC_FILES))

# Object files from source files
OBJECTS = $(SOURCES:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)

# Create output directories if they don't exist
$(shell mkdir -p $(OBJ_DIR) $(BIN_DIR))

# Default target: Compile and link everything
all: $(EXEC)

# Link the object files into the final executable
$(EXEC): $(OBJECTS)
	$(CC) $(OBJECTS) -o $(EXEC) $(LDFLAGS)

# Compile each .c file into a .o object file
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
	$(CC) $(CFLAGS) $(INCLUDE_DIR) -c $< -o $@

# Build with size optimization
size-opt: CFLAGS += -ffunction-sections -fdata-sections
size-opt: LDFLAGS += -Wl,--gc-sections -s
size-opt: clean all
	@echo "Built with additional size optimizations"

# Build without testing code
release: CFLAGS := $(filter-out -DTESTING_BUILD,$(CFLAGS))
release: clean all
	@echo "Built release version (no testing code)"

# Clean up object files and the executable
clean:
	rm -rf $(OBJ_DIR)/*.o $(EXEC)

# Optional: Run the program after building
run: $(EXEC)
	./$(EXEC)

# Show current configuration
info:
	@echo "Build configuration:"
	@echo "  USE_SCHANNEL: $(USE_SCHANNEL)"
	@echo "  Testing build: $(filter -DTESTING_BUILD,$(CFLAGS))"
	@echo "  Source files: $(notdir $(SOURCES))"
	@echo "  CFLAGS: $(CFLAGS)"
	@echo "  LDFLAGS: $(LDFLAGS)"
	@echo "  INCLUDE_DIR: $(INCLUDE_DIR)"

install:
	@echo "Install target not implemented."

.PHONY: all clean run info install size-opt release
