# Configuration
CC=gcc
CFLAGS=-Wall -Wextra -std=gnu99 -D_GNU_SOURCE
RELEASE_FLAGS=-O2
DEBUG_FLAGS=-g -O0 -DDEBUG
LIBS=-lgpiod
TARGET=gpio_service
SRCDIR=src
SOURCES=$(SRCDIR)/gpio_service.c
BINDIR=/usr/local/bin
SERVICEDIR=/etc/systemd/system

# Cible par défaut (release)
$(TARGET): $(SOURCES)
	$(CC) $(CFLAGS) $(RELEASE_FLAGS) -o $(TARGET) $(SOURCES) $(LIBS)

# Cible debug
debug: CFLAGS += $(DEBUG_FLAGS)
debug: $(TARGET)
	@echo "🔧 Version DEBUG compilée (symboles: -g, optimisation: -O0)"

# Cible release
release: CFLAGS += $(RELEASE_FLAGS)
release: $(TARGET)
	@echo "🚀 Version RELEASE compilée (optimisation: -O2)"

# Installation
install: $(TARGET)
	@echo "📦 Installation du service GPIO..."
	sudo install -d $(BINDIR)
	sudo install -m 755 $(TARGET) $(BINDIR)/
	sudo install -m 644 gpio-service.service $(SERVICEDIR)/
	sudo systemctl daemon-reload
	sudo systemctl enable gpio-service
	@echo "✅ Installation terminée"

# Installation version debug
install-debug: debug
	@echo "🐛 Installation version DEBUG..."
	sudo install -d $(BINDIR)
	sudo install -m 755 $(TARGET) $(BINDIR)/
	sudo systemctl daemon-reload
	@echo "✅ Version DEBUG installée"

# Désinstallation
uninstall:
	@echo "🗑️  Désinstallation du service GPIO..."
	sudo systemctl stop gpio-service 2>/dev/null || true
	sudo systemctl disable gpio-service 2>/dev/null || true
	sudo rm -f $(BINDIR)/$(TARGET)
	sudo rm -f $(SERVICEDIR)/gpio-service.service
	sudo systemctl daemon-reload
	sudo rm -f /dev/gpio_service
	@echo "✅ Désinstallation terminée"

# Nettoyage
clean:
	rm -f $(TARGET)
	@echo "🧹 Fichiers de compilation nettoyés"

# Installation et démarrage
setup: install start

start:
	sudo systemctl start gpio-service
	@echo "🚀 Service démarré"

stop:
	sudo systemctl stop gpio-service
	@echo "🛑 Service arrêté"

restart: stop start

status:
	sudo systemctl status gpio-service --no-pager

logs:
	sudo journalctl -u gpio-service -f

# Debug avec GDB
gdb-debug: debug
	@echo "🐛 Lancement avec GDB..."
	sudo systemctl stop gpio-service 2>/dev/null || true
	sudo gdb --args ./$(TARGET)

gdb-attach:
	@echo "🔗 Attachement GDB au processus..."
	sudo gdb -p $(shell pgrep gpio_service)

# Informations
info:
	@echo "📋 Informations de compilation:"
	@echo "   Cible: $(TARGET)"
	@echo "   Compilateur: $(CC)"
	@echo "   Flags: $(CFLAGS)"
	@echo "   Librairies: $(LIBS)"
	@if file $(TARGET) | grep -q debug; then \
		echo "   Type: DEBUG"; \
	else \
		echo "   Type: RELEASE"; \
	fi

.PHONY: all debug release install install-debug uninstall clean setup start stop restart status logs gdb-debug gdb-attach info
