src = $(wildcard *.c)
bins = $(src:.c=) 
perls = $(wildcard *.pl)

all: $(bins)

test: $(bins) $(perls)
	@-mkdir tmp
	@if [ ! "$(MOOLIB)" -o ! -e "../../$(MOOLIB)" ]; then \
		echo cannot find moo lib >&2; \
		false; \
	fi
	@echo Testing wrapping: ;$(foreach test,$(bins) $(perls), \
		./$(test) > $(test).out.1 2>$(test).err.1 </dev/null; \
		RET1=$$?; \
		MOOIX_PROXY_DEBUG=10; export MOOIX_PROXY_DEBUG; \
		LD_PRELOAD=../../$(MOOLIB) ./$(test) > $(test).out.2 2>$(test).err.2 </dev/null; \
		RET2=$$?; \
		FUNC=`head -n 1 $(test).out.1`; \
		printf "	$(test)		"; \
		if [ -z "$$FUNC" ]; then \
			printf "did not output a function name. " >&2; \
			FAILED=1; \
		fi; \
		if ! cmp -s $(test).out.1 $(test).out.2; then \
			printf "stdout differs. " >&2; \
			FAILED=1; \
		fi; \
		if ! grep -q mooix.*: $(test).err.2; then \
			printf "mooix wrapper was not called. " >&2; \
			FAILED=1; \
		fi; \
		if ! egrep -q "mooix.*:\ $$FUNC" $(test).err.2; then \
			printf "mooix wrapper function $$FUNC not called. ">&2; \
			FAILED=1; \
		fi; \
		grep -v "mooix.*:" $(test).err.2 > $(test).err.2.nomoo; \
		if ! cmp -s $(test).err.1 $(test).err.2.nomoo; then \
			printf "stderr differs. " >&2; \
			FAILED=1; \
		fi; \
		if [ "$$RET1" != "$$RET2" ]; then \
			printf "return code differs. ($$RET1 vs $$RET2)" >&2; \
			FAILED=1; \
		fi; \
		echo; \
	) if [ "$$FAILED" ]; then echo "*** Some tests FAILED!" >&2 ; false; else echo "All tests ok. Bravo!"; fi
	

clean:
	rm -f $(bins) *.out.1 *.out.2 *.err.1 *.err.2 *.err.2.nomoo *~
	rm -rf tmp
