JUCE := build/JUCE
NPROC := $(shell sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null || echo 4)
UNAME_S := $(shell uname -s)

ifeq ($(UNAME_S),Darwin)
  AU_DIR := $(HOME)/Library/Audio/Plug-Ins/Components
  VST3_DIR := $(HOME)/Library/Audio/Plug-Ins/VST3
  APP_DIR := /Applications
else
  VST3_DIR := $(HOME)/.vst3
endif

BUILD_DIR := build/Trommelkiste_artefacts

.PHONY: all clean install uninstall

install: all
	@echo "==> Installing plugins..."
ifeq ($(UNAME_S),Darwin)
	@mkdir -p "$(AU_DIR)"
	@for f in $$(find $(BUILD_DIR) -name "*.component" -type d); do \
		echo "  $$f -> $(AU_DIR)/"; \
		rm -rf "$(AU_DIR)/$$(basename "$$f")"; \
		cp -R "$$f" "$(AU_DIR)/"; \
	done
	@mkdir -p "$(VST3_DIR)"
	@for f in $$(find $(BUILD_DIR) -name "*.vst3" -type d); do \
		echo "  $$f -> $(VST3_DIR)/"; \
		rm -rf "$(VST3_DIR)/$$(basename "$$f")"; \
		cp -R "$$f" "$(VST3_DIR)/"; \
	done
	@mkdir -p "$(APP_DIR)"
	@for f in $$(find $(BUILD_DIR) -name "*.app" -type d); do \
		echo "  $$f -> $(APP_DIR)/"; \
		rm -rf "$(APP_DIR)/$$(basename "$$f")"; \
		cp -R "$$f" "$(APP_DIR)/"; \
	done
else
	@mkdir -p "$(VST3_DIR)"
	@for f in $$(find $(BUILD_DIR) -name "*.vst3" -type d); do \
		echo "  $$f -> $(VST3_DIR)/"; \
		rm -rf "$(VST3_DIR)/$$(basename "$$f")"; \
		cp -R "$$f" "$(VST3_DIR)/"; \
	done
endif
	@echo "==> Done."

all: build/Makefile
	@$(MAKE) --no-print-directory -C build -j$(NPROC)
	@echo ""
	@echo "Build complete. Output:"
	@find $(BUILD_DIR) -type d \( -name "*.vst3" -o -name "*.component" -o -name "*.app" \) 2>/dev/null | while read f; do echo "  $$f"; done

build/Makefile: CMakeLists.txt
	@if [ ! -f "$(JUCE)/CMakeLists.txt" ]; then \
		rm -rf "$(JUCE)"; \
		echo "==> Cloning JUCE..."; \
		git clone --depth 1 https://github.com/juce-framework/JUCE.git $(JUCE); \
	fi
	@echo "==> Configuring CMake..."
	@cmake -B build -DCMAKE_BUILD_TYPE=Release

uninstall:
	@echo "==> Removing installed plugins..."
ifeq ($(UNAME_S),Darwin)
	@for f in $$(find $(BUILD_DIR) -name "*.component" -type d 2>/dev/null); do \
		rm -rf "$(AU_DIR)/$$(basename "$$f")"; \
	done
	@for f in $$(find $(BUILD_DIR) -name "*.vst3" -type d 2>/dev/null); do \
		rm -rf "$(VST3_DIR)/$$(basename "$$f")"; \
	done
	@for f in $$(find $(BUILD_DIR) -name "*.app" -type d 2>/dev/null); do \
		rm -rf "$(APP_DIR)/$$(basename "$$f")"; \
	done
else
	@for f in $$(find $(BUILD_DIR) -name "*.vst3" -type d 2>/dev/null); do \
		rm -rf "$(VST3_DIR)/$$(basename "$$f")"; \
	done
endif
	@echo "==> Done."

clean:
	rm -rf build
