# Build lib/libsprinter.lib — the Sprinter target libc archive.
#
# Includes all libc/*.c modules plus the runtime helpers that get
# auto-pulled by SDCC's codegen (heap for malloc, bank trampolines for
# __banked).  The crt0 family is NOT in the lib — they are always
# explicitly linked, never DCE-eligible.
#
# Each .c file becomes its own .rel inside the archive.  The linker
# pulls only those .rel files whose exported symbols are referenced,
# giving free dead-code elimination at module granularity.

PROJ_ROOT := $(abspath $(CURDIR)/..)
SDCC_BIN  := $(PROJ_ROOT)/third_party/sdcc/bin
SDCC      := $(SDCC_BIN)/sdcc
SDAR      := $(SDCC_BIN)/sdar
SDASZ80   := $(SDCC_BIN)/sdasz80

INC       := -I$(PROJ_ROOT)/libc/include
CC_FLAGS  := -mz80 --no-std-crt0 --std-c99 --opt-code-size $(INC)

BUILD     := $(PROJ_ROOT)/lib/build

# All libc C modules — every .c under libc/<area>/ becomes its own .rel.
# One PUBLIC function per file (see docs/libc-split-asm-cases.md): the
# linker pulls whole .rel modules, so file granularity == DCE granularity.
LIBC_C := $(patsubst $(PROJ_ROOT)/%,%,$(wildcard $(PROJ_ROOT)/libc/*/*.c))

# Runtime modules to bundle (pulled by symbol references from libc-using code).
# NOTE: runtime/bank.s is NOT bundled — its trampoline depends on the banking
# window (W1 for BIG, W3 for HUGE) which is decided per-build by sprinter-cc.
# That tool assembles bank.s on each banked build with the right BANK_W1 flag.
RUNTIME_S := runtime/heap.s

LIBC_RELS    := $(patsubst libc/%.c,$(BUILD)/%.rel,$(LIBC_C))
RUNTIME_RELS := $(patsubst runtime/%.s,$(BUILD)/%.rel,$(RUNTIME_S))

ALL_RELS := $(LIBC_RELS) $(RUNTIME_RELS)

# Штамп списка модулей: обновляется при любом изменении состава
# (добавление/удаление/переименование исходника) — иначе удаление
# исходника не триггерит перелинковку и stale .rel остаётся в архиве.
# Сразу сносим и архив: на exFAT (SAM8) гранулярность mtime грубая,
# и «список изменился» через сравнение времён можно проглядеть.
MODLIST := $(BUILD)/.modules
ifneq ($(shell cat $(MODLIST) 2>/dev/null),$(ALL_RELS))
_ := $(shell mkdir -p $(BUILD); echo "$(ALL_RELS)" > $(MODLIST); rm -f sprinter.lib)
endif

LIB := sprinter.lib

all: $(LIB)

# Pattern rule for C modules — preserves the libc/io|mem|stdio path
# so .rel members keep their natural names inside the archive.
$(BUILD)/%.rel: $(PROJ_ROOT)/libc/%.c
	@mkdir -p $(dir $@)
	$(SDCC) $(CC_FLAGS) -c -o $@ $<

# Runtime .s → .rel
$(BUILD)/%.rel: $(PROJ_ROOT)/runtime/%.s
	@mkdir -p $(dir $@)
	$(SDASZ80) -o $@ $<

# Archive — sdar with `rcs` = replace/create/symtab.
# Перед упаковкой удаляем stale .rel: wildcard не знает об удалённых/
# переименованных исходниках, и осиротевший .rel из build/ иначе жил бы
# вечно (уже кусало: старый file.rel после сплита).
$(LIB): $(ALL_RELS) $(MODLIST)
	@find $(BUILD) -name '*.rel' -print | sort > $(BUILD)/.have
	@printf '%s\n' $(ALL_RELS) | sort > $(BUILD)/.want
	@comm -23 $(BUILD)/.have $(BUILD)/.want | while read f; do \
	    echo "  stale: $$f (исходник удалён) — rm"; \
	    rm -f "$$f" "$${f%.rel}.asm" "$${f%.rel}.lst" "$${f%.rel}.sym"; \
	done
	rm -f $@
	$(SDAR) -rcs $@ $(ALL_RELS)
	@echo
	@echo "  Built $@ with $(words $(ALL_RELS)) modules:"
	@$(SDAR) -t $@ | sed 's/^/    /'

clean:
	rm -rf $(BUILD) $(LIB)

.PHONY: all clean
