CXX?=g++
NODE?=$(shell (which node || which nodejs || echo 0))
INSTDIR?=$(DESTDIR)/usr/lib
PYTHON?=python
GYP?=$(shell which node-gyp 2>/dev/null || echo vendor/node-gyp/bin/node-gyp.js 2>/dev/null)
NODE_VERSION?=0.10.9
DEBIAN?=$(shell (grep -qi debian /etc/lsb-release &>/dev/null || test -e /etc/debian_version ) && echo 1)
LINKSTEMMER=$(shell pwd)/vendor/libstemmer_c/libstemmer.a

# we want to build in c++11 mode, but on some compilers that are still around this is still referred to as c++0x 
# @TODO clang compat
GCCSTD?=$(shell ($(CXX) -std=c++11 -x c++ -E -v - </dev/null 2>/dev/null >/dev/null && echo c++11) || ($(CXX) -std=c++0x -x c++ -E -v - </dev/null 2>/dev/null >/dev/null && echo c++0x) || echo 0)

ifeq ($(GCCSTD), 0)
all:
	# @TODO clang compat
	$(error Unable to determine which standard flag to use to enable C++11 mode. You can define GCCSTD appropriately to solve this. Also, be sure you have g++ installed.)
else
all: node vendor/libstemmer_c/libstemmer.a gypconfig
	$(NODE) $(GYP) build 
endif

tmptest: text.o text_tree.o
	g++ -DHG_TMP_DEBUG -Wall -Wextra -Weffc++ -std=c++11 -lstemmer -licuuc -licui18n -lboost_regex -lboost_system -lboost_filesystem t.cc text.o text_tree.o -o t
	./t
text.o: text.cc text.h
	g++ -DHG_TMP_DEBUG -Wall -Wextra -Weffc++ -std=c++11 -c ./text.cc -o text.o
text_tree.o: text_tree.cc text_tree.h
	g++ -DHG_TMP_DEBUG -Wall -Wextra -Weffc++ -std=c++11 -c ./text_tree.cc -o text_tree.o

gypconfig:
	$(NODE) $(GYP) configure

vendor/libstemmer_c/libstemmer.a:
	cd vendor/libstemmer_c && make

baseclean:
	-rm -r build
	-rm *.o
	cd vendor/libstemmer_c && make clean

vendor/node-gyp/bin/node-gyp.js: 
	cd .. && \
	git submodule init source/vendor/node-gyp && \
	git submodule update

ifeq ($(NODE), 0)
NODE=vendor/node/stage/bin/node
ifeq ($(shell test -e $(NODE) || echo 0), 0)
node: $(GYP)
	cd .. && \
	git submodule init source/vendor/node && \
	git submodule update
	cd vendor/node && \
	git checkout origin/v$(NODE_VERSION)-release && \
	./configure --prefix=stage && \
	make install
else
node: $(GYP)
	true
endif
clean: baseclean
	cd vendor/node && make clean
	-rm -r vendor/node/stage
else
node: $(GYP)
	true
clean: baseclean
	true
endif

install: build/Release/hubgraph.node
	install -d $(DESTDIR)/lib/node_modules --mode 0755
	install build/Release/hubgraph.node $(DESTDIR)/lib/node_modules --mode 0755

# not really needed with packages, but if you're just installing with make you can use this target to bring in dependencies that are packaged for your distro
ifeq ($(DEBIAN), 1)
deps:
	apt-get install libboost-filesystem-dev libboost-regex-dev libboost-serialization-dev libboost-graph-dev libboost-system-dev libicu-dev
else
deps:
	yum install boost-devel boost-regex boost-serialization boost-graph boost-system libicu-devel
endif
