################################################################################
# initialization
################################################################################

# detect os
OS := $(shell uname -s | tr [:upper:] [:lower:])

# detect bit size
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_M),x86_64)
	ARCH := 64
else
	ARCH := 32
endif

# aliases
JAR   := jar
JAVA  := java
JAVAC := javac
MKDIR := mkdir -p
MV := mv
RM := rm -rf
ifeq ($(OS),darwin)
	# MacOS
	LIBEXT := dylib
else
	# linux
	LIBEXT := so
endif

# set JAVA_HOME, if it's unset or blank
ifeq ($(JAVA_HOME),)
	ifeq ($(OS),darwin)
		# MacOS
		JAVA_HOME := $(shell /usr/libexec/java_home)
	else
		# linux
		JAVA_HOME := $(shell $(JAVA) -XshowSettings:properties -version 2>&1 > /dev/null | grep "java.home" | cut -d"=" -f2 | tr -d [:space:])
	endif
endif

# color definitions
blue := $(shell tput setaf 6)
sgr0 := $(shell tput sgr0)


################################################################################
# compilation parameters
################################################################################

# define output file
OUT := slbmtest.jar
OUTDIR := ../bin


################################################################################
# recipes
################################################################################

# recipe to make everything and run tests
all: initialize slbmtest finalize

# command that tells us which recipes don't build source files
.PHONY: all initialize msg_intro slbmtest finalize clean cleanall
	

# initialize compilation script
initialize: msg_intro

# print intro message
msg_intro:
	@echo "$(blue)------------------------------------------------------------$(sgr0)"
	@echo "$(blue)Making RSTT Java test...$(sgr0)"
	@echo "$(blue)------------------------------------------------------------$(sgr0)"


# build library
slbmtest: slbmtest.jar

slbmtest.jar: build/slbmtest/SLBMTest.class
	@printf "$(blue)(Building jar) $(sgr0)"
	$(JAR) -cmf src/MANIFEST.mf $(OUT) -C build slbmtest/SLBMTest.class -C .. lib/slbmjni.jar

build/slbmtest/SLBMTest.class: build src/slbmtest/SLBMTest.java
	@printf "$(blue)(Compiling java) $(sgr0)"
	$(JAVAC) -cp ../lib/slbmjni.jar -d build src/slbmtest/SLBMTest.java

build:
	@printf "$(blue)(Make directory) $(sgr0)"
	$(MKDIR) build


# move files and clean up
finalize:
	@printf "$(blue)(Moving files) $(sgr0)"
	$(MV) $(OUT) $(OUTDIR)


clean:
	@printf "$(blue)(Clean *.class) $(sgr0)"
	$(RM) build

cleanall: clean
	@printf "$(blue)(Clean bin) $(sgr0)"
	$(RM) $(OUTDIR)/$(OUT)
