#SIMGRID_INSTALL_DIR ?= $(PWD)/simgrid-stable
SIMGRID_INSTALL_DIR ?= $(PWD)/simgrid-dev

OPTIM_FLAGS += -pipe -O3
DEBUG_FLAGS += -g
#DEBUG_FLAGS += -pg
CHECK_FLAGS += -Wall -Wextra

CC := gcc
CXX := g++

CPPFLAGS += -I $(SIMGRID_INSTALL_DIR)/include
CPPFLAGS += $(CHECK_FLAGS)

#CFLAGS += -std=c99
#CFLAGS += -fgnu89-inline      # workaround simgrid bug
CFLAGS += $(OPTIM_FLAGS) $(DEBUG_FLAGS)

CXXFLAGS += -std=c++11
CXXFLAGS += $(OPTIM_FLAGS) $(DEBUG_FLAGS)

LDFLAGS += -L $(SIMGRID_INSTALL_DIR)/lib
LDFLAGS += -Wl,-rpath,$(SIMGRID_INSTALL_DIR)/lib

LINK.o = $(CXX) $(CXXFLAGS) $(LDFLAGS) $(TARGET_ARCH)
LDLIBS := -lsimgrid -lrt

MAKEDEPEND.FLAGS =  $(CPPFLAGS) -MM -MG -MF $@ $<
MAKEDEPEND.C = $(CC) $(CFLAGS) $(MAKEDEPEND.FLAGS)
MAKEDEPEND.CXX = $(CXX) $(CXXFLAGS) $(MAKEDEPEND.FLAGS)

SRC.loba := main.cpp		\
	communicator.cpp	\
	cost_func.cpp		\
	deployment.cpp		\
	hostdata.cpp		\
	$(wildcard loba_*.cpp)	\
	messages.cpp		\
	misc.cpp		\
	msg_thread.cpp		\
	neighbor.cpp		\
	options.cpp		\
	process.cpp		\
	version.cpp

SRC := $(SRC.loba)
OBJ := $(SRC:%.cpp=%.o)
DEP := $(SRC:%.cpp=.%.d)

DEFAULT_TARGETS := loba
FLAVOURED_LOBA := loba-dev loba-stable
TARGETS := $(DEFAULT_TARGETS)

.PHONY: all full clean realclean $(FLAVOURED_LOBA)

all: $(DEFAULT_TARGETS)

full:
	@for target in $(FLAVOURED_LOBA); do	\
		echo $(MAKE) "$$target";	\
		$(MAKE) "$$target";		\
	done
	$(MAKE) $(DEFAULT_TARGETS)

clean:
	$(RM) core core.[0-9]* vgcore.[0-9]*
	$(RM) localversion
	$(RM) $(OBJ)
	$(RM) $(DEP)
	$(RM) $(TARGETS)

realclean: clean
	$(RM) $(FLAVOURED_LOBA)
	$(RM) *~

.%.d: %.c ; $(MAKEDEPEND.C)

.%.d: %.cpp ; $(MAKEDEPEND.CXX)

$(FLAVOURED_LOBA):
	$(MAKE) clean
	$(MAKE) SIMGRID_INSTALL_DIR=$(PWD)/simgrid-$(patsubst loba-%,%,$@) loba
	mv -f -- loba $@
	$(MAKE) clean

version.o: $(patsubst %.cpp,%.o,$(filter-out version.cpp, $(SRC.loba)))

ifeq ($(filter $(MAKECMDGOALS),full clean realclean $(FLAVOURED_LOBA)),)
  $(shell ./setlocalversion)
  -include $(DEP)
endif

.SECONDEXPANSION:
$(TARGETS): $$(patsubst %.cpp,%.o,$$(SRC.$$@))
	$(LINK.o) $^ $(LOADLIBES) $(LDLIBS) -o $@