include ../buildconf.mk

HWDB_INPUT := $(wildcard udev/*.hwdb)
HWDB_GEN := gen_database.sh
HWDB_BUILD_INPUT := $(patsubst udev/%.hwdb,$(BUILD_HWDB)/input/%.hwdb,$(HWDB_INPUT))
HWDB_BUILD_GEN := $(patsubst %,$(BUILD_HWDB)/%,$(HWDB_GEN))
HWDB_BUILD := $(BUILD_HWDB)/hwdb.squashfs

HWDB_INSTALL := $(INSTALL_HWDB)/hwdb.squashfs 

# Default: copy prebuilt hwdb/hwdb.squashfs if present (fast). If absent, do nothing — run
# `make all-full` here or `make all` from the project root to regenerate (slow).
.PHONY: all all-full
all:
	@if [ -f hwdb.squashfs ]; then $(MAKE) --no-print-directory $(HWDB_BUILD); \
	else echo "hwdb: skipped (no hwdb.squashfs in hwdb/; run: make all-full)" >&2; fi

# Full rebuild from *.hwdb sources (slow; requires mksquashfs and gen_database.sh inputs).
all-full:
	$(MAKE) --no-print-directory $(HWDB_BUILD) HWDB_FULL=1

$(HWDB_BUILD): $(HWDB_BUILD_INPUT) $(HWDB_BUILD_GEN)
	@set -e; \
	if [ -f hwdb.squashfs ] && [ "$(HWDB_FULL)" != "1" ]; then \
		cp -a hwdb.squashfs "$@"; \
	elif [ "$(HWDB_FULL)" = "1" ]; then \
		echo "Generating hardware database"; \
		mkdir -p "$@.dir"; \
		$(BUILD_HWDB)/gen_database.sh -o "$@.dir" $(BUILD_HWDB)/input/*.hwdb; \
		mksquashfs "$@.dir" "$@" -force-uid 0 -force-gid 0; \
	else \
		echo "hwdb.squashfs: build requires hwdb/hwdb.squashfs or HWDB_FULL=1 (see make all-full)" >&2; \
		exit 1; \
	fi

$(BUILD_HWDB)/input/%.hwdb: udev/%.hwdb
	@mkdir -p "$(shell dirname "$@")"
	@cp -a "$<" "$@"

$(BUILD_HWDB)/%.sh: %.sh
	@mkdir -p "$(shell dirname "$@")"
	@cp -a "$<" "$@"

.PHONY: install
install: $(HWDB_INSTALL)

$(INSTALL_HWDB)/%: $(BUILD_HWDB)/%
	mkdir -p "$(shell dirname "$@")"
	cp -a "$<" "$@"

.PHONY: uninstall
uninstall:
	rm -f "$(HWDB_INSTALL)"

.PHONY: clean 
clean:
	rm -rf $(HWDB_BUILD) $(HWDB_BUILD_INPUT) $(HWDB_BUILD_GEN) $(HWDB_BUILD).dir

print-%: ; @echo $*=$($*)

