SRCDIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
JULIAHOME := $(abspath $(SRCDIR)/../..)
BUILDDIR := .
include $(JULIAHOME)/Make.inc

JCFLAGS += $(CFLAGS)
JCXXFLAGS += $(CXXFLAGS)
JCPPFLAGS += $(CPPFLAGS)
JLDFLAGS += $(LDFLAGS)

SRCS := hashing timefuncs ptrhash operators utf8 ios htable bitvector \
	int2str libsupportinit arraylist strtod rle
ifeq ($(OS),WINNT)
SRCS += asprintf strptime
ifeq ($(ARCH),i686)
SRCS += _setjmp.win32
else ifeq ($(ARCH),x86_64)
SRCS += _setjmp.win64
endif
endif

HEADERS := $(wildcard *.h) $(LIBUV_INC)/uv.h

OBJS := $(SRCS:%=$(BUILDDIR)/%.o)
DOBJS := $(SRCS:%=$(BUILDDIR)/%.dbg.obj)

FLAGS := $(HFILEDIRS:%=-I%) -I$(LIBUV_INC) -I$(UTF8PROC_INC) -DJL_LIBRARY_EXPORTS_INTERNAL -DUTF8PROC_EXPORTS
FLAGS += -Wall -Wno-strict-aliasing -fvisibility=hidden -Wpointer-arith -Wundef
JCFLAGS += -Wold-style-definition -Wstrict-prototypes -Wc++-compat

DEBUGFLAGS += $(FLAGS)
SHIPFLAGS += $(FLAGS)

default: release

$(BUILDDIR):
	mkdir -p $(BUILDDIR)

$(BUILDDIR)/%.o: $(SRCDIR)/%.c $(HEADERS) | $(BUILDDIR)
	@$(call PRINT_CC, $(CC) $(JCPPFLAGS) $(JCFLAGS) $(SHIPFLAGS) $(DISABLE_ASSERTIONS) -c $< -o $@)
$(BUILDDIR)/%.dbg.obj: $(SRCDIR)/%.c $(HEADERS) | $(BUILDDIR)
	@$(call PRINT_CC, $(CC) $(JCPPFLAGS) $(JCFLAGS) $(DEBUGFLAGS) -c $< -o $@)
$(BUILDDIR)/%.o: $(SRCDIR)/%.S | $(BUILDDIR)
	@$(call PRINT_CC, $(CC) $(JCPPFLAGS) $(SHIPFLAGS) -c $< -o $@)
$(BUILDDIR)/%.dbg.obj: $(SRCDIR)/%.S | $(BUILDDIR)
	@$(call PRINT_CC, $(CC) $(JCPPFLAGS) $(DEBUGFLAGS) -c $< -o $@)

$(BUILDDIR)/host/Makefile:
	mkdir -p $(BUILDDIR)/host
	@# add Makefiles to the build directories for convenience (pointing back to the source location of each)
	@echo '# -- This file is automatically generated in julia/Makefile -- #' > $@
	@echo 'BUILDDIR=$(BUILDDIR)/host' >> $@
	@echo 'BUILDING_HOST_TOOLS=1' >> $@
	@echo 'include $(SRCDIR)/Makefile' >> $@

release: $(BUILDDIR)/libsupport.a
debug: $(BUILDDIR)/libsupport-debug.a

$(BUILDDIR)/libsupport.a: $(OBJS) | $(BUILDIR)
	rm -rf $@
	@$(call PRINT_LINK, $(AR) -rcs $@ $^)

$(BUILDDIR)/libsupport-debug.a: $(DOBJS) | $(BUILDDIR)
	rm -rf $@
	@$(call PRINT_LINK, $(AR) -rcs $@ $^)

$(BUILDDIR)/host/libsupport.a: $(BUILDDIR)/host/Makefile
	$(MAKE) -C $(BUILDDIR)/host libsupport.a

$(BUILDDIR)/host/libsupport-debug.a: $(BUILDDIR)/host/Makefile
	$(MAKE) -C $(BUILDDIR)/host libsupport-debug.a

clean:
	rm -f $(BUILDDIR)/*.o
	rm -f $(BUILDDIR)/*.dbg.obj
	rm -f $(BUILDDIR)/*.a
	rm -f $(BUILDDIR)/*~ *#
	rm -f $(BUILDDIR)/core*
	rm -f $(BUILDDIR)/libsupport.a
	rm -f $(BUILDDIR)/libsupport-debug.a
	rm -f $(BUILDDIR)/host/*
