CC := cc
PKG_CONFIG := pkg-config

TARGET := build/linuxSmartie

BITCHY_ERRORS := \
	-Wconversion \
    -Wsign-conversion \
    -Wshadow \
    -Wformat=2 \
    -Wundef \
    -Wstrict-prototypes \
    -Wmissing-prototypes \
    -Wold-style-definition \
    -Wwrite-strings \
    -Wvla \
    -Wcast-qual \
    -Wcast-align \
    -Wpointer-arith \
    -Wswitch-enum \

CFLAGS := \
	-std=c23 \
	-Iinclude \
	-Ibuild \
	-D_GNU_SOURCE \
	-D_POSIX_C_SOURCE=200809L \
	-Wall \
	-Wextra \
	-Wpedantic \
	-Werror \
	-pedantic-errors \
	-MMD -MP \
    -O2 \
    $(BITCHY_ERRORS)


LDLIBS := \
	$(shell $(PKG_CONFIG) --libs libusb-1.0) \
	-lm

SOURCES := $(wildcard src/*.c)
OBJECTS := $(patsubst src/%.c,build/src/%.o,$(SOURCES))
DEPS := $(OBJECTS:.o=.d)

VERSION_H := build/version.h

# glowny target, linkuje linuxSmartie, potrzebuje ${OBJECTS}, jest na samej górze wiec jest domyslny
$(TARGET): $(OBJECTS) $(VERSION_H)
	$(CC) $(OBJECTS) -o $@ $(LDLIBS)

# Compile source files
build/src/%.o: src/%.c $(VERSION_H)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

# Generate version.h from Git
$(VERSION_H): include/version.h.in
	@mkdir -p $(dir $@)
	@version=$$(git describe --always --long --dirty 2>/dev/null || echo unknown); \
	sed "s/@VCS_TAG@/$$version/" $< > $@.tmp; \
	if ! cmp -s $@.tmp $@ 2>/dev/null; then \
		mv $@.tmp $@; \
	else \
		rm -f $@.tmp; \
	fi

# Include automatically generated header dependencies
-include $(DEPS)

.PHONY: all clean install uninstall debug

all: $(TARGET)

debug: CFLAGS += -O0 -g
debug: $(TARGET)

clean:
	rm -rf build

install: $(TARGET)
	install -Dm755 $(TARGET) $(DESTDIR)$(HOME)/.local/bin/linuxSmartie

install_service: install
	mkdir -p ~/.config/systemd/user
	cp linuxSmartie.service ~/.config/systemd/user/linuxSmartie.service
	systemctl --user daemon-reload
	systemctl --user enable linuxSmartie
	systemctl --user start linuxSmartie

uninstall:
	rm -f $(DESTDIR)$(HOME)/.local/bin/linuxSmartie