ARCH=$(notdir $(CURDIR))
ifeq (,$(filter _%,$(ARCH)))
# tar --hard-dereference --exclude='_*/*' -czf

.SUFFIXES:

all_arches = $(wildcard _*)

MAKETARGET = $(MAKE) --no-print-directory -C $@ -f $(CURDIR)/Makefile \
                     SRCDIR=$(CURDIR)/ $(MAKECMDGOALS)

.PHONY: $(all_arches)

all: $(all_arches) $(patsubst %,%/phony,$(foreach x,$(syncdirs),$x))



$(patsubst %,%/phony,$(foreach x,$(syncdirs),$x)):
	rsync -t -v -r --exclude '_*' . $(patsubst %/phony,%,$@)

$(all_arches):
	+@echo arch $@
	+@$(MAKETARGET)

Makefile :

% :: $(all_arches) ;

.PHONY: tarball
tarball:
	@DIR=$(lastword $(subst /, ,$(shell pwd))) && \
	NOW=`date +%Y%m%d%H%M%S` && \
	cd .. && pwd && \
	echo "Creating tarball $$DIR-$$NOW.tar.gz" && \
	tar --exclude='_*/*' -czf $$DIR-$$NOW.tar.gz $$DIR/ && \
	ln -sf $$DIR-$$NOW.tar.gz $$DIR.tar.gz

else
VPATH = $(SRCDIR)
CC=$(CC$(ARCH))
AR=$(AR$(ARCH))
CFLAGS=$(CFLAGS$(ARCH))
LDFLAGS=$(LDFLAGS$(ARCH))

tarball:

%.md5.c: %
	@echo "static char inf1[] = \"\$$md5:\" __DATE__ \" \" __TIME__ \" $(shell md5sum $<) \";" >> $@
	@echo "static char inf2[] = \"\$$md5:\" __DATE__ \" \" __TIME__ \"" $(shell $(CC) -E $(CPPFLAGS) $(CFLAGS) $< | md5sum) "$<\";" >> $@

%.d: %.c
	@set -e; rm -f $@; \
	$(CC) -MM $(CPPFLAGS) $< | \
	sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g'  > $@;

%.de: Makefile
	@echo "$(patsubst %.de,%,$@): $(patsubst %.c,%.o,$(foreach x,$(patsubst %.de,%,$@),$($(x)))) $(patsubst %,%.md5.o,$(foreach x,$(patsubst %.de,%,$@),$($(x))))" > $@

%.ds: Makefile
	@echo -e "product/$(patsubst %.ds,%,$@)$(ARCH): $(patsubst %.ds,%,$@)" >$@
	@echo -e "\tcp $(patsubst %.ds,%,$@) ../product/$(patsubst %.ds,%,$@)$(ARCH)" >> $@

clean:
	rm -f *.o $(products) $(products2) *.exe *~ *.d *.de *.ds *.md5.c *.gcda *.gcno gmon.out *.gcov

snap_sources = $(sort $(foreach x,$(all),$($(x))))
all_sources = $(snap_sources) $(md5_sources)
all_headers = $(wildcard *.h)
all_docs = $(wildcard *.txt)
products =  $(foreach x,$(all),$(x))
products2 =  $(foreach x,$(all),product/$(x)$(ARCH))

all:	$(products) $(products2) 

ifneq ($(MAKECMDGOALS),clean)
include $(all_sources:.c=.d)
-include $(products:=.de)
-include $(products:=.ds)
endif
endif
# The purpose of this makefile:
# 1. build each architecture in its own target directory
# 2. automatically generate header file dependencies
# 3. automatically insert compilation date/time and md5sum of each source file
#    only the actual files linked to the binary are included, although there is
#    a separate md5 for each file's preprocessed source.
# 4. sync sources and products to snapshot directories
# 5. make it really simple to create a makefile (e.g. see dioctl/Makefile)
