################################################################################
# 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
CC := gcc
MV := mv
RM := rm -rf
ifeq ($(OS),darwin)
	# MacOS
	LIBEXT := dylib
else
	# linux
	LIBEXT := so
endif

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


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

# define output file
OUT := slbmtestc
OUTDIR := ../bin

# includes
INC := -I../GeoTessCPP/include -I../SLBM/include -I../SLBM_C_shell/include

# libraries
LIBDIR := ../lib
LIBS := -lm -lstdc++ -L$(LIBDIR) -lgeotesscpp -lslbm -lslbmCshell

# compiling parameters
CCFLAGS = -march=native -D$(OS) -m$(ARCH) -O1

# list of objects to compile
OBJS = src/slbmtestc.o


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

# recipe to make everything
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 C test...$(sgr0)"
	@echo "$(blue)------------------------------------------------------------$(sgr0)"


# to build any *.o file, compile its corresponding *.cc file
%.o: %.c
	@printf "$(blue)(Building obj) $(sgr0)"
	$(CC) $(CCFLAGS) $(INC) -o $@ -c $<


# build library after building each prerequisite in $(OBJS)
slbmtest: initialize $(OUT)

# MacOS
ifeq ($(OS),darwin)
$(OUT): $(OBJS)
	@printf "$(blue)(Building lib) $(sgr0)"
	$(CC) $(CCFLAGS) -Wl,-rpath,"@executable_path/$(LIBDIR)" -o $(OUT) $^ $(LIBS)

# linux
else
$(OUT): $(OBJS)
	@printf "$(blue)(Building lib) $(sgr0)"
	$(CC) $(CCCFLAGS) -Wl,-rpath,'$$ORIGIN/$(LIBDIR)' -o $(OUT) $^ $(LIBS)

endif


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

clean:
	@printf "$(blue)(Clean *.o) $(sgr0)"
	$(RM) src/*.o

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