#
# Coretest makefile for macOS
#

# The Xcode configuration: Debug or Release
CONFIG ?= Release

# Following sets the location of the wx-config command
# WX_BUILD_DIR is set by the GitHub workflow
# Override this to use a local build
ifdef WX_BUILD_DIR
WX_CONFIG := $(WX_BUILD_DIR)/bin/wx-config
else ifdef HOMEBREW_PREFIX
WX_CONFIG := $(HOMEBREW_PREFIX)/bin/wx-config
endif

# Get the location of the Xcode built libraries (core and os)
XRELDIR := $(shell xcodebuild -project ../../Xcode/pwsafe-xcode6.xcodeproj -showBuildSettings -scheme pwsafe -configuration $(CONFIG) | awk '/TARGET_BUILD_DIR =/{print $$3}')

BUILD		:= $(CONFIG)

TESTSRC         := coretest.cpp $(wildcard *Test.cpp)

OBJPATH         = ../../obj/$(BUILD)
LIBPATH         = $(XRELDIR)
BINPATH         = ./bin
INCPATH         = ..

# Assumes Googletest was installed via Homebrew
# brew install googletest
GTEST_DIR     = $(HOMEBREW_PREFIX)/include/googletest/googletest
GTEST_HEADERS = $(HOMEBREW_PREFIX)/include/gtest/*.h $(HOMEBREW_PREFIX)/include/gtest/internal/*.h
GTEST_SRCS_   = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)
GTEST_OBJ = $(OBJPATH)/gtest-all.o

#destination related macros
TESTOBJ	 = $(addprefix $(OBJPATH)/,$(subst .cpp,.o,$(TESTSRC)))
TEST	 = $(BINPATH)/coretest
OBJS     = $(TESTOBJ) $(GTEST_OBJ)

CXXFLAGS += -DUNICODE -Wall -I$(INCPATH) -I$(INCPATH)/core -std=c++17 -I $(HOMEBREW_PREFIX)/include
LDFLAGS  += -L$(LIBPATH) -lcore -los 

ifeq ($(CONFIG),Debug)
LDFLAGS += `$(WX_CONFIG) --debug=yes --unicode=yes --libs`
else ifeq ($(CONFIG),Release)
LDFLAGS += `$(WX_CONFIG) --debug=no --unicode=yes --libs`
endif

# rules
.PHONY: all clean test run setup

$(OBJPATH)/%.o : %.c
	$(CC) -g  $(CFLAGS)   -c $< -o $@

$(OBJPATH)/%.o : %.cpp
	$(CXX) -g $(CXXFLAGS) -c $< -o $@

all : setup test

$(GTEST_OBJ): $(GTEST_SRCS_) $(GTEST_HEADERS)
	$(CXX) -g $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c -o $@ \
	$(GTEST_DIR)/src/gtest-all.cc


run test : $(TEST)
	$(TEST)

$(TEST): $(LIB) $(OBJS)
	$(CXX) -g $(CXXFLAGS) $(filter %.o,$^) $(LDFLAGS) -o $@

clean:
	rm -f *~ $(OBJPATH)/*.o $(TEST) $(DEPENDFILE)

setup:
	@mkdir -p $(OBJPATH) $(LIBPATH) $(BINPATH)
	@echo "Xcode build location: $(XRELDIR)"
	@echo "WX_CONFIG location: $(WX_CONFIG)"
	@echo
	@[ -x $(WX_CONFIG) ] || echo "ERROR: wx-config not found: Need to define the path to the wx-config command (WX_CONFIG variable)\n"
