SOURCES=$(wildcard *.cc)
TARGETS=$(addprefix bin/, $(SOURCES:.cc=))
RESULTS=$(addprefix log/, $(SOURCES:.cc=.success))

#
# Linux / gcc
#
ifeq ($(shell uname -s), Linux)
CC=g++
CCFLAGS=-I../include -I../libv8/include -I../../swlib-cc/include -std=c++11 -pedantic -g -pg -O3 -DV8_DEPRECATION_WARNINGS
LDFLAGS=../libv8/lib/libv8-native.a -lrt -pg
GPROF_PROFILES=$(addprefix log/, $(SOURCES:.cc=.gprof))
PERF_PROFILES=$(addprefix log/, $(SOURCES:.cc=.perf))
endif

#
# BSD, clang
#
ifeq ($(shell uname -s), FreeBSD)
CC=clang++
CCFLAGS=-std=c++11 -pedantic -g -O3 -I../include -I../../swlib-cc/include -I/usr/local/include -DV8_DEPRECATION_WARNINGS
LDFLAGS=-L/usr/local/lib -lv8 -lrt
GPROF_PROFILES=
PERF_PROFILES=
endif

#
# MacOS, clang
#
ifeq ($(shell uname -s), Darwin)
endif

.PHONY: clean build all prep

all: build run
clean: ; @rm -rf bin; rm -rf log
build: prep $(TARGETS) bin/test.js
run: prep $(RESULTS) bin/test.js
	@rm -f gmon.out
	@rm -f *.perf
	
profiling: build run bin/test.js $(GPROF_PROFILES) $(PERF_PROFILES) 
	@rm -f gmon.out
	@rm -f *.perf

prep:
	@mkdir -p log
	@mkdir -p bin

#
# Version determination
#
bin/v8version: aux/v8version.cc
	-@mkdir -p bin
	-@$(CC) $< -o $@ $(CCFLAGS) $(LDFLAGS)

#
# Test js files
#
bin/%.js: %.js
	@cp $< $@

#
# Test run log files
#
log/%.success: bin/% bin/%.js bin/test.js
	@rm -f $(basename $@).failed
	-@if [ $(shell cd bin && "./$(notdir $<)" >../$@ 2>&1 3>&1; echo "$$?") -eq 0 ]; then \
	  echo "[success]" "$(notdir $<)"; \
	else \
	  mv $@ $(basename $@).failed; \
	  echo "[failed ]" "$(notdir $<)"; cat $(basename $@).failed | sed 's/^/        | /'; \
	fi
#
# Binaries
#
bin/%: %.cc test.hh ../include/v8i.hh bin/v8version
	@echo "[build  ]" $@
	-@$(CC) $< -o $@ $(CCFLAGS) $(LDFLAGS) $(shell bin/v8version -d)
	-@cp $(basename $<).js $@.js

ifneq ($(GPROF_PROFILES),)
#
# Profiling using gprof
#
log/%.gprof: bin/% bin/%.js bin/test.js
	@if [ -z "$(shell which gprof)" ]; then echo "[error  ] --> install gprof"; fi
	@echo "[gprof  ]" $<
	-@cd bin; gprof -b "./$(notdir $<)" >../$@; rm -f bin/gmon.out

#
# Profiling using perf
#
log/%.perf: bin/% bin/%.js bin/test.js
	@if [ -z "$(shell which perf)" ]; then echo "[error  ] --> install linux-tools, perf"; fi
	@echo "[perf   ]" $<
	-@cd bin; perf record -qgs "./$(notdir $<)" >/dev/null 2>&1 3>&1; \
		  perf report >../$@ 2>/dev/null; rm -f bin/perf.data
endif
