-include Makefile.def
.PHONY: all clean FORCE depend lib daemon server client_caca client_gl

#Aliases
.DEFAULT_GOAL := everything
everything: all
lib: lib$(NAME).so
daemon server: $(NAME)d
client-caca: $(NAME)
client-gl: $(NAME)-gl

#FORCE target... do not remove
FORCE:

H_CONFIGS = $(subst ./,,$(shell find . -name "config*.h.in" -and -not -path './test/*'))
$(H_CONFIGS:.h.in=.h): FORCE $(@:.h=.h.in)
	@if [ ! -f .configured ]; then\
		$(ECHO) -e '\033[32mConfiguring';\
		$(RST);\
	fi
	@sed -e "s/\$${SVN_REV}/${SVN_REV}/g"\
		-e "s/\$${SERVER_RES_PATH}/${SERVER_RES_PATH}/g"\
		-e "s/\$${LIB_RES_PATH}/${LIB_RES_PATH}/g"\
		-e "s/\$${CLIENT_GL_RES_PATH}/${CLIENT_GL_RES_PATH}/g"\
		-e "s/\$${CLIENT_CACA_RES_PATH}/${CLIENT_CACA_RES_PATH}/g"\
		$@.in >$@.temp
	@cmp -s $@.temp $@ || (if [ ! -f .configured ]; then echo "Revision update detected"; fi; mv $@.temp $@)
	@touch .configured
	@rm -f $@.temp

sizeof.h:
	@($(CC) -o test/sizeof test/sizeof.c) && (test/sizeof > sizeof.h)
	
# source list:
C_SOURCES = $(subst ./,,$(shell find . -name "*.c" -and -not -path './test/*'))
CC_SOURCES = $(subst ./,,$(shell find . -name "*.cpp" -and -not -path './test/*'))

#compiler and linker calls respecting dependencies
all $(NAME)d $(NAME) $(NAME)-gl lib$(NAME).so: sizeof.h depend FORCE
	$(MAKE) $(MAKEFLAGS) -f Makefile.inner $@

help:
	@$(ECHO) -e "\nMake targets:"
	@$(ECHO) -e "lib\t(a.k.a. libmmpong.so)\n\t-- Builds the mmpong shared library, on which all the other targets are based"
	@$(ECHO) -e "server\t(a.k.a. daemon, mmpongd)\n\t-- Builds the daemon binary"
	@$(ECHO) -e "client-caca\t(a.k.a. mmpong)\n\t-- Builds the libcaca-based client"
	@$(ECHO) -e "client-gl\t(a.k.a. mmpong-gl)\n\t-- Builds the SDL-based client"
	@$(ECHO) -e "flags\n\t-- Show the compiler flags to be used during the build"

flags:
	@$(ECHO) -e '\nCompiles with SERVER_CFLAGS:\n$(SERVER_CFLAGS)\n'
	@$(ECHO) -e 'Links with SERVER_LDLIBS:\n$(SERVER_LDLIBS)\n'
	@$(ECHO) -e '\nCompiles with CLIENT_CACA_CFLAGS:\n$(CLIENT_CACA_CFLAGS)\n'
	@$(ECHO) -e 'Links with CLIENT_CACA_LDLIBS:\n$(CLIENT_CACA_LDLIBS)\n'
	@$(ECHO) -e '\nCompiles with CLIENT_GL_CFLAGS:\n$(CLIENT_GL_CFLAGS)\n'
	@$(ECHO) -e 'Links with CLIENT_GL_LDLIBS:\n$(CLIENT_GL_LDLIBS)\n'

#dependency resolver
depend: FORCE $(H_CONFIGS:.h.in=.h)
	@$(ECHO) -e '\033[32mResolving dependencies\033[31m'
	@rm -f .configured .Makefile.depend
ifneq ("$(strip $(C_SOURCES))","")
	@$(CC) $(ALL_CFLAGS) -I. -MM $(C_SOURCES) 2>/dev/null | sed -e 's/.*: \(.*\/\).*\.c/\1\0/' | sed -e 's/.*:/build\/&/' >> .Makefile.depend
endif
ifneq ($(strip $(CC_SOURCES)),)
	@$(CXX) $(ALL_CXXFLAGS) -I. -MM $(CC_SOURCES) 2>/dev/null | sed -e 's/.*: \(.*\/\).*\.cpp/\1\0/' | sed -e 's/.*:/build\/&/' >> .Makefile.depend
endif
	@$(RST)

clean:	
	@rm -rf $(OBJDIR)
	@rm -f $(NAME) $(NAME)-gl $(NAME)d lib$(NAME).so .Makefile.depend test/sizeof sizeof.h */config.h
#	@rm -rf ./doc/
