# uni-json Makefile
#

#*  definitions
#**  programs
#
GCC :=		gcc
CC :=		$(GCC) -Iinclude
LD :=		$(GCC)
AR :=		ar
INST_D :=	install -m 0644
INST_X :=	install -m 0755

#**  files
#
SRCS :=		$(shell ls src/*.c)
OBJS :=		$(addprefix tmp/, $(notdir $(SRCS:.c=.o)))
DEPS :=		$(OBJS:.o=.d)

STATIC_DIR :=	tmp/static
STATIC_OBJS :=	$(addprefix $(STATIC_DIR)/, $(notdir $(SRCS:.c=.o)))
STATIC_DEPS :=	$(STATIC_OBJS:.o=.d)

HDRS :=		$(addprefix include/, \
	uni_json_p_binding.h \
	uni_json_parser.h \
	uni_json_s_binding.h \
	uni_json_serializer.h \
	uni_json_types.h \
)

#**  library
#
V_MAJ :=	1
V_MIN :=	1

L_BASE :=	libuni-json.so
L_MAJ :=	$(L_BASE).$(V_MAJ)
LIB :=		$(L_MAJ).$(V_MIN)
LIB_A :=	libuni-json.a

#**  CFLAGS
#
CFLAGS :=	-g -W -Wall -Wno-pointer-sign -Wno-implicit-fallthrough

ifndef DEV
CFLAGS :=	-O2 $(CFLAGS)
endif

# Optional flags from parent (e.g. vdev: make SANITIZE=1 passes ASan CFLAGS here).
EXTRA_CFLAGS ?=
CFLAGS += $(EXTRA_CFLAGS)

EXTRA_LDFLAGS ?=

#**  installation
#
PREFIX :=	$(shell . ./PREFIX && printf '%s' "$$PREFIX")

MULTI :=	$(shell gcc -print-multiarch)

TARGET :=	$(DESTDIR)$(PREFIX)
TARGET_LIB :=	$(TARGET)/lib/$(MULTI)
TARGET_INC :=	$(TARGET)/include

#**  lib version
#

#*  targets
#
.PHONY: all clean install

all: bin/$(L_MAJ) bin/$(L_BASE) bin/$(LIB_A)

tmp bin $(STATIC_DIR):
	mkdir -p $@

install: all
	$(INST_X) -d $(TARGET_INC) $(TARGET_LIB)
	$(INST_D) $(HDRS) $(TARGET_INC)
	$(INST_D) bin/$(LIB) $(TARGET_LIB)
	$(INST_D) bin/$(LIB_A) $(TARGET_LIB)
	cd $(TARGET_LIB) && ln -sf $(LIB) $(L_MAJ) && ln -sf $(LIB) $(L_BASE)

clean:
	-rm -rf tmp bin

bin/$(LIB): $(OBJS) | bin

bin/$(L_MAJ) bin/$(L_BASE): bin/$(LIB)
	ln -sf $(notdir $^) $@

bin/$(LIB_A): $(STATIC_OBJS) | bin
	$(AR) rcs $@ $(STATIC_OBJS)

include $(DEPS) $(STATIC_DEPS)

#*  %-rules
#
tmp/%.d: src/%.c | tmp
	$(CC) -MM $< | perl -pe 's|$*\.o|$@|' >$@

tmp/%.o: src/%.c tmp/%.d | tmp
	$(CC) $(CFLAGS) -fpic -c -o $@ $<

$(STATIC_DIR)/%.d: src/%.c | $(STATIC_DIR)
	$(CC) -MM $< | perl -pe 's|$*\.o|$@|' >$@

$(STATIC_DIR)/%.o: src/%.c $(STATIC_DIR)/%.d | $(STATIC_DIR)
	$(CC) $(CFLAGS) -c -o $@ $<

bin/%: | bin
	$(LD) $(EXTRA_LDFLAGS) -shared -o $@ -Wl,-soname -Wl,$(notdir $(basename $@)) $^
