#================================================================================
TARGET_NAME = libvlkbcommon.a
VERSION ?= $(shell git describe)
BUILD_ ?= $(shell LANG=us_US date; hostname)
#================================================================================
DEPS_DIR := ../../ext/nlohmann-json
DEPS_INC := $(DEPS_DIR)/include
#DEPS_LIB := $(DEPS_DIR)/lib
#================================================================================
INC_DIR=src include $(DEPS_INC) \
	/usr/include/cfitsio \
	/usr/include/postgresql
#================================================================================
CC=g++
CXX_DEBUG_FLAGS=-g -DFDB_DEBUG
CXX_RELEASE_FLAGS=-O2
CXX_DEFAULT_FLAGS=-c -x c++ -std=c++11 -fPIC -Wall -Wextra -Wconversion -fno-common -DVERSIONSTR='"$(VERSION)"' -DBUILD='"$(BUILD_)"'
INC_PARM=$(foreach d, $(INC_DIR), -I$d)
#================================================================================
SRC_DIR:=src
OBJ_DIR:=obj
LIB_DIR:=lib
#================================================================================
TARGET 		:= $(LIB_DIR)/$(TARGET_NAME)
CPP_FILES 	:= $(wildcard $(SRC_DIR)/*.cpp)
C_FILES 		:= $(wildcard $(SRC_DIR)/*.c)
OBJ_FILES   := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o)))
C_OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(C_FILES:.c=.o)))
# defer eval when objs were created 
DEPS_OBJ_FILES = $(wildcard $(DEPS_DIR)/obj/*.o)
#================================================================================
NPROCS = $(shell grep -c 'processor' /proc/cpuinfo)
MAKEFLAGS += -j$(NPROCS)
#================================================================================
.PHONY: all
all : debug

.PHONY: release
release: CXXFLAGS+=$(CXX_RELEASE_FLAGS) $(CXX_DEFAULT_FLAGS)
release: $(TARGET)

.PHONY: debug
debug: CXXFLAGS+=$(CXX_DEBUG_FLAGS) $(CXX_DEFAULT_FLAGS)
debug: $(TARGET)


$(TARGET) : makedir $(DEPS_OBJ_FILES) $(DEPS_LIB) $(OBJ_FILES) $(C_OBJ_FILES)
	ar -rc $@ $(DEPS_OBJ_FILES) $(OBJ_FILES) $(C_OBJ_FILES)

.PHONY : $(DEPS_LIB)
$(DEPS_LIB):
	make -C $(DEPS_DIR)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
	        $(CC) $(CXXFLAGS) $(INC_PARM) -o $@ $<

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
	        $(CC) $(CXXFLAGS) $(INC_PARM) -o $@ $<


.PHONY: makedir
makedir:
	-mkdir -p $(OBJ_DIR) $(LIB_DIR)


.PHONY: clean_deps
clean_deps:
	#make -C $(DEPS_DIR) clean

.PHONY: clean
clean : clean_deps
	-rm -fr $(OBJ_DIR) $(LIB_DIR)


.PHONY: test
test :
	@tabs 20
	@echo -e "TARGET_NAME:\t"  $(TARGET_NAME)
	@echo -e "VERSION:\t"  $(VERSION)
	@echo -e "CPP_FILES:\t"  $(CPP_FILES)
	@echo -e "OBJ_FILES:\t"  $(OBJ_FILES)
	@echo -e "C_FILES:\t"  $(C_FILES)
	@echo -e "C_OBJ_FILES:\t"  $(C_OBJ_FILES)
	@echo -e "INC_PARM:\t"  $(INC_PARM)


