include project.mk

SHELL := /bin/sh
SUFFIXES :=

all: all-programs

INCPATH += $(patsubst %,-I%,$(MODULES))
MODFILES := $(patsubst %,%/module.mk,$(MODULES))
PROGRAMS :=

# Hide commands?
ifeq ($(HUSH),1)
override HUSH := @
else
override HUSH :=
endif

# Include module descriptions
include.mk: Makefile project.mk
	@echo "* Generating include.mk..."
	$(HUSH)echo '# This file is automatically generated by make' >\
			include.mk;\
	echo '# Do not edit; changes will be lost' >> include.mk;\
	for mod in $(MODULES); do\
	echo '' >> include.mk;\
	echo 'PRE := '$$mod'' >> include.mk;\
	echo 'include '$$mod'/module.mk' >> include.mk;\
	done;\
	echo '' >> include.mk;\
	echo '-include auto.mk' >> include.mk
-include include.mk

# This had to be deferred to after including module definitions
all-programs: $(PROGRAMS)

# Generate nifty automatic stuff
auto.mk: Makefile project.mk $(MODFILES)
	@echo "* Generating auto.mk..."
	$(HUSH)echo '# This file is automatically generated by make' > auto.mk;\
	echo '# Do not edit; changes will be lost' >> auto.mk;\
	for prog in $(PROGRAMS); do\
	echo '' >> auto.mk;\
	echo '# Program: '$$prog'' >> auto.mk;\
	echo 'OBJ-'$$prog' := $$(patsubst %.c,%.o,$$(filter\
			%.c,$$(SRC-'$$prog')))' >> auto.mk;\
	echo 'DEP-'$$prog' := $$(patsubst %.c,%.d,$$(filter\
			%.c,$$(SRC-'$$prog')))' >> auto.mk;\
	echo 'SRC += $$(SRC-'$$prog')' >> auto.mk;\
	echo 'OBJ += $$(OBJ-'$$prog')' >> auto.mk;\
	echo 'DEP += $$(DEP-'$$prog')' >> auto.mk;\
	echo ''$$prog': $$(OBJ-'$$prog')' >> auto.mk;\
	echo -e '\t@echo "* Linking $$@..."' >> auto.mk;\
	echo -e '\t$$(HUSH)$$(CC) $$(CFLAGS) $$(LDFLAGS) $$(LIBPATH) -o $$@'\
			'$$(OBJ-'$$prog') $$(LIBS-'$$prog')'\
			'$$(LIBS)' >> auto.mk;\
	done;\
	echo '' >> auto.mk;\
	echo '# Include dependencies' >> auto.mk;\
	echo 'ifneq ($$(MAKECMDGOALS),clean)' >> auto.mk;\
	echo '-include $$(DEP)' >> auto.mk;\
	echo 'endif' >> auto.mk

# Generate object and dependency files from source
%.d %.o: %.c
	@echo "* Compiling $<..."
	$(HUSH)$(CC) $(CFLAGS) $(CPPFLAGS) $(INCPATH) -MMD -c -o\
			$(patsubst %.d,%.o,$@) $<
	$(if $(filter-out .o,$(suffix $@)),$(HUSH)sed 's/^/$(subst /,\/,$@\
	$(dir $@))/' $(notdir $@) > .tmp.$(subst /,.,$@);\
	rm -f $(notdir $@);\
	mv -f .tmp.$(subst /,.,$@) $@)

# Remove generated files
clean:
	@echo "* Removing generated files..."
	$(HUSH)-rm -f core $(PROGRAMS) $(OBJ) include.mk auto.mk $(DEP)

# Tell make about special (non-file) targets
.PHONY: all clean