# Tests conf_general_detect_apply_all_foc's handling of the flux linkage
# measurement (conf_general.c).
#
# The function is cut out of the real source rather than copied, together with
# the two wait helpers and the dual-motor worker tasks above it, so it cannot
# drift from what the firmware compiles. The measurements, the motor interface
# and the sensor detection are stubbed in main.c. Built twice: single motor,
# and HW_HAS_DUAL_MOTORS, where the second motor's linkage is measured by a
# worker task.
#
# The extraction is checked: if a marker moves, the build fails rather than
# testing an empty file.

TOP = ../..
SRC = $(TOP)/conf_general.c

CFLAGS = -std=gnu99 -O1 -g -Wall -Wextra -Wno-unused-function \
         -fsanitize=address,undefined -fno-omit-frame-pointer \
         -DNO_STM32 -I. -I$(TOP) -I$(TOP)/util
LIBS = -lm

all: test test-dual

detect.inc: $(SRC) Makefile
	@awk '/^static bool wait_fault\(int timeout_ms\) \{$$/ { on = 1 } \
		on { print } \
		on && /^int conf_general_detect_apply_all_foc\(/ { in_fn = 1 } \
		in_fn && /^}$$/ { exit }' $(SRC) > $@
	@grep -q '^int conf_general_detect_apply_all_foc(' $@ || { echo \
		"detect.inc has no conf_general_detect_apply_all_foc: a marker in"\
		" $(SRC) changed, so the extraction needs updating"; rm -f $@; exit 1; }
	@tail -1 $@ | grep -q '^}$$' || { echo "detect.inc looks truncated"; \
		rm -f $@; exit 1; }
	@grep -q 'measure_flux_linkage_task' $@ || { echo \
		"detect.inc has no dual-motor linkage task"; rm -f $@; exit 1; }

test: main.c detect.inc
	gcc $(CFLAGS) -o $@ main.c $(LIBS)

test-dual: main.c detect.inc
	gcc $(CFLAGS) -DHW_HAS_DUAL_MOTORS -o $@ main.c $(LIBS)

run: test test-dual
	@echo "--- single motor ---"
	./test
	@echo "--- dual motor ---"
	./test-dual

clean:
	rm -f test test-dual detect.inc

.PHONY: all run clean
