include ../../../buildconf.mk

C_SRCS := $(filter-out common.c, $(wildcard *.c))
CXSRCS:= $(wildcard *.cpp)
OBJ   := $(patsubst %.c,$(BUILD_VDEVD_HELPERS)/%.o,$(C_SRCS)) $(patsubst %.cpp,$(BUILD_VDEVD_HELPERS)/%.o,$(CXSRCS))
LIB   := -pthread -lrt -lblkid `pkg-config --libs libinput libudev` -L$(BUILD_LIBVDEV) -lvdev
CFLAGS += `pkg-config --cflags libinput libudev`

HELPER_SCRIPTS := $(wildcard *.sh)
HELPERS := stat_optical stat_ata stat_input stat_scsi stat_path stat_net stat_v4l \
	stat_usb stat_bus event-put echo_n cdrom_id vdev_block_info vdev_root_sys_block \
	vdev_settle daemonlet $(HELPER_SCRIPTS)

HELPERS_BUILD := $(patsubst %,$(BUILD_VDEVD_HELPERS)/%,$(HELPERS))
HELPERS_INSTALL := $(patsubst %,$(INSTALL_VDEVD_HELPERS)/%,$(HELPERS))

LIBVDEV := $(BUILD_LIBVDEV)/libvdev.a

all: $(HELPERS_BUILD)

# Prefer the build-tree binary; block Make's built-in "%.c → ./daemonlet" rule.
.PHONY: daemonlet
daemonlet: $(BUILD_VDEVD_HELPERS)/daemonlet

$(BUILD_VDEVD_HELPERS)/%: $(BUILD_VDEVD_HELPERS)/%.o $(LIBVDEV)
	@mkdir -p "$(shell dirname "$@")"
	$(CC) -o "$@" $< $(LIBINC) $(LIB) $(LDFLAGS)

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

$(BUILD_VDEVD_HELPERS)/%.sh: %.sh
	@mkdir -p "$(shell dirname "$@")"
	cp -a "$<" "$@"
	chmod a+x "$@"

install: $(HELPERS_INSTALL)
$(INSTALL_VDEVD_HELPERS)/%: $(BUILD_VDEVD_HELPERS)/%
	@mkdir -p "$(shell dirname "$@")"
	@rm -f "$@"
	cp -a "$<" "$@"

.PHONY: uninstall
uninstall:
	rm -f $(HELPERS_INSTALL)

.PHONY: clean
clean:
	rm -f $(OBJ) $(HELPERS_BUILD)
	rm -f daemonlet
