# zxedit — Makefile
CC      ?= cc
PREFIX  := $(if $(filter 0,$(shell id -u)),/usr/local,$(HOME)/.local)
BINDIR  := $(DESTDIR)$(PREFIX)/bin

CPPFLAGS += -D_POSIX_C_SOURCE=200809L -DUNITY_INCLUDE_DOUBLE
CPPFLAGS += -Isrc -Isrc/core -Ivendor/unity/src
CFLAGS   ?= -Wall -Wextra -Werror -std=c17 -g -fno-omit-frame-pointer
CFLAGS   += -fsanitize=address,undefined
LDLIBS   += -lm

CORE_SRC  := $(wildcard src/core/*.c)
UI_SRC    := $(wildcard src/ui/*.c)
TEST_SRC  := $(filter-out tests/test_main.c,$(wildcard tests/*.c))

BIN_SRC   := $(CORE_SRC) $(UI_SRC) src/zxedit_tui.c

.PHONY: all test test-pty clean install uninstall

all: test bin/zxedit

bin:
	@mkdir -p $@

# --- test suite (Unity, generated runner) ---
# Place a freshly linked binary with a guaranteed exec bit: remove any
# stale $@.tmp first (cc keeps the mode of an existing file), link, then
# mv (rename never touches permissions, so mounts that reject chmod
# still work). test -x catches a umask that stripped the exec bit.
LINKED = @mv -f $@.tmp $@ && test -x $@ || { echo "ERROR: $@ has no exec bit after build"; false; }

bin/test_zxedit: $(TEST_SRC) tests/test_main.c vendor/unity/src/unity.c $(CORE_SRC) $(UI_SRC) | bin
	rm -f $@.tmp
	$(CC) $(CFLAGS) $(CPPFLAGS) tests/test_main.c \
		vendor/unity/src/unity.c $(CORE_SRC) $(UI_SRC) -o $@.tmp $(LDLIBS)
	$(LINKED)

tests/test_main.c: tools/gen_runner.sh $(TEST_SRC)
	tools/gen_runner.sh > $@

test: bin/test_zxedit
	ASAN_OPTIONS=detect_leaks=0 ./bin/test_zxedit

# --- main binary ---
# PTY-driven interaction tests (milestone 4)
test-pty: bin/zxedit
	python3 tests/pty_zxedit.py

bin/zxedit: $(BIN_SRC) | bin
ifeq ($(strip $(BIN_SRC)),)
	@echo "ERROR: no sources yet (core not implemented)" >&2; exit 1
endif
	rm -f $@.tmp
	$(CC) $(CFLAGS) $(CPPFLAGS) $(BIN_SRC) -o $@.tmp $(LDLIBS)
	$(LINKED)

install: bin/zxedit
	mkdir -p $(BINDIR)
	cp bin/zxedit $(BINDIR)/zxedit   # cp keeps the 755 mode of the build

uninstall:
	rm -f $(BINDIR)/zxedit

clean:
	rm -rf bin

# Distribution archive from HEAD, always after 'make clean' (Martin,
# 2026-12-01). Output: ../zxedit.zip (override with ZIP_OUT=).
ZIP_OUT  ?= ../zxedit.zip
ZIP_EXCLUDE := err
zip: clean
	git archive -o $(ZIP_OUT) --prefix=zxedit/ HEAD -- . \
		$(foreach p,$(ZIP_EXCLUDE),':(exclude)$(p)')
