include toprules.make

#include default config
include Makefile.conf-default
#if exists, include local config which overrides defaults
ifneq ($(shell ls Makefile.conf 2>/dev/null),)
include Makefile.conf
endif

versrcs = Version.cpp
verhdrs = Colyseus.h
verobjs = $(shell ls $(versrcs) | \
		perl -pne 's|(.*)/([^/]*)\.cpp|$$1/.$$2.o|')

wansrcs = $(wildcard $(patsubst %,%/*.cpp,$(wandirs)))
wanhdrs = $(wildcard $(patsubst %,%/*.h,$(wandirs)))
wanobjs = $(shell ls $(wansrcs) | \
		perl -pne 's|(.*)/([^/]*)\.cpp|$$1/.$$2.o|')

ifeq ($(make_wan),YES)
subdirs += $(wandirs)
TARGETS += wan
endif
ifeq ($(make_wanarchive),YES)
subdirs += $(wandirs)
TARGETS += wan-archive
endif

SUBDIRS = $(shell echo $(subdirs) | tr '\\ ' '\n' | sort | uniq | tr '\n' ' ')
APPDIRS += $(appdirs)
MERCLIB = $(MERCDIR)/libmerc-wan.so
MERCLD  = -lmerc-wan

###############################################################################

all: config.h $(TARGETS) $(APPDIRS)

wantarg     = libcolyseus-wan$(LIBEXT)
wanarchivetarg = libcolyseus-wan.a

wan: $(wantarg)
wan-archive: $(wanarchivetarg)

config.h:
	@./configure

precompile:
ifeq ($(RELEASE),release)
	@-rm -f $(verobjs)
endif

version: precompile $(verobjs)

###############################################################################

$(wantarg): $(version) $(MERCLIB) $(SUBDIRS)
ifneq ($(MAKECMDGOALS),clean)
	@echo "+ Linking $@"
 ifeq  ($(OS),Linux)
	@$(CPP) -shared $(OPTFLAGS) -Wl,-soname,$(wantarg) -o $@ $(verobjs) $(wanobjs) $(LDFLAGS) $(MERCLD)
 else
 ifeq  ($(OS),Darwin)
	@$(CPP) -dynamiclib $(OPTFLAGS) -o $(wantarg) $(verobjs) $(wanobjs) $(LDFLAGS) $(MERCLD)
 else
 ifeq  ($(OS),Win32)
	ERROR # XXX: Dunno what to do on windows
 else
	ERROR
 endif
 endif
 endif
endif

$(wanarchivetarg): $(version) $(SUBDIRS)
ifneq ($(MAKECMDGOALS),clean)
	@echo "+ Archiving $@"
	@ar rc $@ $(verobjs) $(wanobjs)
	@ranlib $@
endif

$(APPDIRS): $(TARGETS)

###############################################################################

cleanables += config.h 
clean: $(SUBDIRS) $(APPDIRS) 

doc: doxygen/doxygen.conf doxygen/doxygen.css $(versrcs)
	doxygen doxygen/doxygen.conf

DIST_FILES = om gameapi \
      demo/* tests apps doxygen/* \
      run *.cpp *.h distmake.sh Makefile* *.make \
      AUTHORS BUGS COPYING README* 

include botrules.make
