include ../buildconf.mk

C_SRCS := $(wildcard *.c) $(wildcard os/*.c) $(wildcard ../libvdev/*.c)
          
INC += -I./helpers/LINUX

LIB   := -lpthread -lrt
OBJ   := $(patsubst %.c,$(BUILD_VDEVD)/%.o,$(C_SRCS))
VDEVD := $(BUILD_VDEVD)/vdevd
VDEV_HELPERS_COMMON_OBJ := $(BUILD_LIBVDEV)/vdev-helpers-common.o

MANPAGES_INSTALL := $(patsubst debian/%,$(INSTALL_MAN8DIR)/%.gz,$(wildcard debian/*.8))

VDEVD_INSTALL := $(INSTALL_VDEVD)/vdevd

HELPERS_DIR := helpers/$(OS)
DMIDECODE_BUILTIN := $(BUILD_VDEVD_HELPERS)/dmidecode-chassis-type-builtin

HWDB_DIR := $(ROOT_DIR)/hwdb

all: $(VDEVD) helpers

$(VDEVD): $(OBJ) helpers $(UNIJSON_LIB) $(VDEV_HELPERS_COMMON_OBJ)
	@mkdir -p "$(shell dirname "$@")"
	$(CC) -o $@ $(OBJ) $(UNIJSON_LIB) $(VDEV_HELPERS_COMMON_OBJ) $(LIB) $(LIBINC) $(LDFLAGS)

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

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

$(BUILD_MAN8DIR):
	@echo "===== MKDIR $@"
	@mkdir -p $@

$(BUILD_MAN8DIR)/%.gz: debian/% | $(BUILD_MAN8DIR)
	gzip < $< > $@

$(INSTALL_MAN8DIR):
	@mkdir -p $@

$(INSTALL_MAN8DIR)/%: $(BUILD_MAN8DIR)/% | $(INSTALL_MAN8DIR)
	@cp $< $@

.PHONY: helpers
helpers: $(BUILD_LIBVDEV)/libvdev.a $(DMIDECODE_BUILTIN)
	$(MAKE) -C $(HELPERS_DIR) all

$(BUILD_LIBVDEV)/libvdev.a:
	$(MAKE) -C $(ROOT_DIR)/libvdev PREFIX=

$(VDEV_HELPERS_COMMON_OBJ): | $(BUILD_LIBVDEV)
	$(MAKE) -C $(ROOT_DIR)/libvdev PREFIX=
$(DMIDECODE_BUILTIN):
	$(MAKE) -C $(ROOT_DIR)/third-party/dmidecode-builtin PREFIX=$(PREFIX)

.PHONY: helpers-install hwdb-install
helpers-install: helpers
	$(MAKE) -C $(HELPERS_DIR) install
	@mkdir -p $(INSTALL_VDEVD_HELPERS)
	@cp -a $(DMIDECODE_BUILTIN) $(INSTALL_VDEVD_HELPERS)/

hwdb-install:
	$(MAKE) -C $(HWDB_DIR) install

conf-install:
	$(MAKE) -C ../example -f conf.mk conf-install

install: $(VDEVD_INSTALL) helpers-install hwdb-install $(MANPAGES_INSTALL) \
	conf-install

$(VDEVD_INSTALL): $(VDEVD)
	@mkdir -p $(INSTALL_VDEVD)
	@rm -f "$@"
	cp -a "$<" "$@"

.PHONY: clean
clean:
	rm -f $(OBJ) $(VDEVD)
	$(MAKE) -C $(ROOT_DIR)/third-party/dmidecode-builtin clean
	$(MAKE) -C $(HELPERS_DIR) clean

.PHONY: uninstall
uninstall:
	rm -f $(VDEVD)
	$(MAKE) -C $(HELPERS_DIR) uninstall
