# Makefile for unlzx - LZX Archive Extractor
# Author: Based on original unlzx.c by various contributors
# Updated with security fixes and modern compilation practices

# Compiler and flags
CC = gcc
CFLAGS = -Wall -Wextra -O2 -std=c99
DEBUG_CFLAGS = -Wall -Wextra -g -O0 -std=c99 -DDEBUG
LDFLAGS = 

# Target executable
TARGET = unlzx

# Source files
SOURCES = unlzx.c

# Object files (derived from sources)
OBJECTS = $(SOURCES:.c=.o)

# Default target
all: $(TARGET)

# Build the main executable
$(TARGET): $(OBJECTS)
	$(CC) $(OBJECTS) -o $(TARGET) $(LDFLAGS)

# Compile source files to object files
%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

# Debug build
debug: CFLAGS = $(DEBUG_CFLAGS)
debug: $(TARGET)

# Clean build artifacts
clean:
	rm -f $(OBJECTS) $(TARGET)

# Install the executable (requires root/sudo)
install: $(TARGET)
	install -m 755 $(TARGET) /usr/local/bin/

# Uninstall the executable (requires root/sudo)
uninstall:
	rm -f /usr/local/bin/$(TARGET)

# Test compilation with strict warnings
test: CFLAGS += -Werror -Wpedantic
test: $(TARGET)
	@echo "Compilation test passed with strict warnings!"

# Security-focused build with additional hardening
secure: CFLAGS += -D_FORTIFY_SOURCE=2 -fstack-protector-strong -Wformat -Wformat-security
secure: LDFLAGS += -Wl,-z,relro,-z,now
secure: $(TARGET)

# Static analysis (if available)
analyze:
	@if command -v cppcheck >/dev/null 2>&1; then \
		cppcheck --enable=all --std=c99 $(SOURCES); \
	else \
		echo "cppcheck not found, skipping static analysis"; \
	fi

# Show help
help:
	@echo "Available targets:"
	@echo "  all      - Build the unlzx executable (default)"
	@echo "  debug    - Build with debug symbols and no optimization"
	@echo "  clean    - Remove build artifacts"
	@echo "  install  - Install to /usr/local/bin (requires sudo)"
	@echo "  uninstall- Remove from /usr/local/bin (requires sudo)"
	@echo "  test     - Build with strict warnings as errors"
	@echo "  secure   - Build with security hardening flags"
	@echo "  analyze  - Run static analysis (requires cppcheck)"
	@echo "  help     - Show this help message"

# Declare phony targets
.PHONY: all debug clean install uninstall test secure analyze help

# Dependencies (auto-generated, but we only have one source file)
unlzx.o: unlzx.c
