CC = gcc
CFLAGS ?= -std=c11 -Wall -Wextra -Wpedantic -O2
CFLAGS_PROFIL ?= -std=c11 -Wall -Wextra -Wpedantic -O0 -g -pg

SOURCE = banque.c
PROGRAMME = build/banque
PROGRAMME_PROFIL = build/profil/banque
EMPREINTE_ATTENDUE = ff68d260a7a58441
NOM ?= $(shell whoami)

.PHONY: all run check test bench profile clean help

all: $(PROGRAMME)

$(PROGRAMME): $(SOURCE) Makefile
	mkdir -p $(@D)
	$(CC) $(CPPFLAGS) $(CFLAGS) $< -o $@ $(LDFLAGS) $(LDLIBS)

run: $(PROGRAMME)
	cd build && ./banque

check: $(PROGRAMME)
	cd build && ./banque > sortie.txt
	@cat build/sortie.txt
	@empreinte=$$(awk '/^Empreinte/ {print $$NF}' build/sortie.txt); \
	if [ "$$empreinte" != "$(EMPREINTE_ATTENDUE)" ]; then \
		printf 'Empreinte incorrecte : %s (attendu %s)\n' "$$empreinte" "$(EMPREINTE_ATTENDUE)" >&2; \
		exit 1; \
	fi
	@printf 'Empreinte correcte.\n'

test: $(SOURCE) tests/test_banque.c
	@programme=$$(mktemp); \
	trap 'rm -f "$$programme"' EXIT HUP INT TERM; \
	$(CC) $(CPPFLAGS) $(CFLAGS) tests/test_banque.c -o "$$programme" $(LDFLAGS) $(LDLIBS) && "$$programme"

# Le script impose gcc -O2, vérifie l'empreinte et mesure 5 exécutions.
bench: $(SOURCE) evaluer.sh
	mkdir -p build
	cd build && bash "$(abspath evaluer.sh)" "$(abspath $(SOURCE))" "$(NOM)"
	@printf 'Mesures disponibles dans build/resultats.csv\n'

$(PROGRAMME_PROFIL): $(SOURCE) Makefile
	mkdir -p $(@D)
	$(CC) $(CPPFLAGS) $(CFLAGS_PROFIL) $< -o $@ $(LDFLAGS) $(LDLIBS)

profile: $(PROGRAMME_PROFIL)
	cd build/profil && ./banque
	cd build/profil && gprof -b ./banque gmon.out > profil.txt
	@printf 'Profil disponible dans build/profil/profil.txt\n'

clean:
	rm -rf build

help:
	@printf '%s\n' \
		'make                 Compiler banque.c avec -O2' \
		'make run             Exécuter et produire build/rapport.txt' \
		"make check           Vérifier l'empreinte attendue" \
		'make test            Vérifier les cas limites des fonctions optimisées' \
		'make bench NOM=nom   Évaluer les performances (médiane de 5 exécutions)' \
		'make profile         Générer le profil gprof avec -O0 -g -pg' \
		'make clean           Supprimer build, y compris les mesures et profils'
