# Makefile.common
#
# Copyright (C) 2012 Michel Pollet <buserror@gmail.com>
#

SHELL			= /bin/bash
INSTALL			?= install
CC				?= gcc
CFLAGS			?= -O2 -Wall

O 				?= .
PREFIX			?= /usr/local

ARCH			:= $(shell $(CC) -dumpmachine)
BUILDNAME		:= build-$(ARCH)
BUILD			:= $(O)/$(BUILDNAME)
OBJ				= $(BUILD)/obj/$(TARGET)
BIN				= $(BUILD)/bin
LIB				= $(BUILD)/lib

DESTDIR			= $(O)/build-$(ARCH)

EXTRA_CFLAGS	+= -g -fPIC --std=gnu99
EXTRA_CFLAGS	+= -ffunction-sections -fdata-sections
EXTRA_CFLAGS	+= ${patsubst %,-I%,${subst :, ,${IPATH}}}

ifeq (${shell uname},Linux)
EXTRA_LDFLAGS	+= -Wl,--relax,--gc-sections
READLINK		= readlink -f
endif
ifeq (${shell uname},Darwin)
READLINK		= echo
endif

ifeq ($(V),1)
Q 				:=
else
Q				:= @
endif

EXTRA_LDFLAGS	+= -L$(LIB) -Wl,-rpath,${shell $(READLINK) ${LIB}}

all: ${OBJ}

#
# Generic rules
#
$(OBJ) $(BIN) $(LIB):
	+$(Q)echo "  MKDIR" $@ && mkdir -p $@

$(LIB)/%.a : | $(LIB)
	$(Q)echo "  LIB   ${@}" && \
	$(AR) cr $@ $^ \
		|| echo Error: $(AR) cru $@ $^

.SECONDARY:

$(OBJ)/%.o: %.c | $(OBJ)
	$(Q)echo "  CC" ${filter -O%, ${EXTRA_CFLAGS} $(CFLAGS) ${CFLAGS_TARGET}} "${<}" && \
	${CC} -MMD ${EXTRA_CFLAGS} ${CPPFLAGS} ${CFLAGS} ${CFLAGS_TARGET} -c -o ${@} ${<} \
		|| echo Error: ${CC} -MD ${EXTRA_CFLAGS} ${CPPFLAGS} ${CFLAGS} ${CFLAGS_TARGET} -c -o ${@} ${<}

$(BIN)/%: $(OBJ)/%.o | $(BIN)
	$(Q)echo "  LD    ${*}" && \
	${CC} -o ${@} $(filter %.o %.a,$^) \
		${EXTRA_LDFLAGS} ${BASE_LDFLAGS} ${LDFLAGS_TARGET} ${LDFLAGS} ${LIBS_${*}} \
		|| echo Error: ${CC} -o $(filter %.o %.a,$^) \
			${EXTRA_LDFLAGS} ${BASE_LDFLAGS} ${LDFLAGS_TARGET} ${LDFLAGS} ${LIBS_${*}}

ifeq (${shell uname},Linux)
define soname
	"-Wl,-soname,$(1)"
endef
else
define soname
endef
endif

$(LIB)/%.so.$(SOV) $(LIB)/%.so.$(VERSION).$(SOV) $(LIB)/%.so: | $(LIB)
	$(Q)echo "  LDSO $@" && \
	{ \
		naked=${shell basename ${basename $@}}; \
		${CC} -shared \
			${call soname,$$naked} \
			-o $(LIB)/$$naked.$(VERSION).$(SOV) \
			$(filter %.o %.a,$^) \
			${EXTRA_LDFLAGS} ${BASE_LDFLAGS} ${LDFLAGS} && \
		ln -sf $$naked.$(VERSION).$(SOV) ${LIB}/$$naked.$(SOV) && \
		ln -sf $$naked.$(SOV) ${LIB}/$$naked ; \
	} || echo ERROR: $@ -- relaunch with V=1

clean::
#	rm -rf $(OBJ) $(BIN)/$(TARGET)
	rm -rf $(BUILD)

# Include autogenerated dependencies
-include ${wildcard $(OBJ)/*.d}
