include ../buildconf.mk

# Keep flags from buildconf.mk (e.g. SANITIZE=1); only add libvdev-specific options.
CFLAGS := $(CFLAGS) -Wall -g -fPIC -fstack-protector -fstack-protector-all -pthread -Wno-unused-variable -Wno-unused-but-set-variable
INC := $(INC) -I$(BUILD_LIBVDEV_HEADERS)
DEFS := $(DEFS) -D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE -D_GNU_SOURCE
CC   := cc

VDEVD_HELPERS_DIR := $(ROOT_DIR)/vdevd/helpers/LINUX
HELPERS_COMMON_SRC := $(VDEVD_HELPERS_DIR)/common.c
HELPERS_COMMON_OBJ := $(BUILD_LIBVDEV)/vdev-helpers-common.o

C_SRCS:= $(wildcard *.c)
HEADERS := $(wildcard *.h)

OBJS := $(patsubst %.c,$(BUILD_LIBVDEV)/%.o,$(C_SRCS)) $(HELPERS_COMMON_OBJ)

LIBVDEV := $(BUILD_LIBVDEV)/libvdev.a
UNIJSON_MERGE := $(BUILD_LIBVDEV)/.uni-json-merge

all: $(LIBVDEV)

$(BUILD_LIBVDEV)/%.o: %.c $(LIBVDEV_HEADERS)
	@mkdir -p "$(shell dirname "$@")"
	$(CC) $(CFLAGS) $(INC) $(DEFS) -o "$@" -c "$<"

$(HELPERS_COMMON_OBJ): $(HELPERS_COMMON_SRC)
	@mkdir -p "$(shell dirname "$@")"
	$(CC) $(CFLAGS) $(INC) $(DEFS) -I$(VDEVD_HELPERS_DIR) -o "$@" -c "$<"

$(LIBVDEV): $(OBJS) $(UNIJSON_LIB)
	rm -rf "$(UNIJSON_MERGE)"
	mkdir -p "$(UNIJSON_MERGE)"
	cd "$(UNIJSON_MERGE)" && ar x $(abspath $(UNIJSON_LIB))
	ar -rcs $@ $(OBJS) "$(UNIJSON_MERGE)"/*.o
	rm -rf "$(UNIJSON_MERGE)"

.PHONY: clean

clean:
	rm -rf "$(UNIJSON_MERGE)"
	rm -f $(OBJS) $(LIBVDEV)

