# Mindball - CMake convenience wrapper
#
#   make               configure and build all plugin formats (AU VST3 Standalone)
#   make install       build, then copy the plugins to the standard locations
#   make clean         remove the build directory
#
# Overrides (as make variables):
#   make BUILD_TYPE=Debug
#   make FORMATS="VST3 LV2"
#   make CMAKE_ARGS="-DJUCE_ROOT=/path/to/juce"
#
# Requires: CMake >= 3.22 and a C++20 compiler. JUCE 8.0.9 is fetched on the
# first configure (or use CMAKE_ARGS="-DJUCE_ROOT=/path/to/juce").

BUILD_DIR  ?= build
BUILD_TYPE ?= Release
FORMATS    ?= AU VST3 Standalone
CMAKE      ?= cmake
CMAKE_ARGS ?= 
JOBS       ?= $(shell sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null || echo 4)

UNAME_S := $(shell uname -s)

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

TARGETS  := $(foreach f,$(FORMATS),Mindball_$(f))
ARTEFACT  = $(BUILD_DIR)/Mindball_artefacts/$(BUILD_TYPE)

.PHONY: all configure build install clean

all: build

configure:
	$(CMAKE) -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) -DMINDBALL_FORMATS="$(FORMATS)" $(CMAKE_ARGS)

build: configure
	$(CMAKE) --build $(BUILD_DIR) -j$(JOBS) --target $(TARGETS)

install: build
	@for f in $(FORMATS); do \
		case "$$f" in \
		VST3) \
			mkdir -p "$(VST3_DIR)" && \
			rm -rf "$(VST3_DIR)/Mindball.vst3" && \
			cp -R "$(ARTEFACT)/VST3/Mindball.vst3" "$(VST3_DIR)/" && \
			echo "Installed: $(VST3_DIR)/Mindball.vst3" ;; \
		AU) \
			if [ -n "$(AU_DIR)" ]; then \
				mkdir -p "$(AU_DIR)" && \
				rm -rf "$(AU_DIR)/Mindball.component" && \
				cp -R "$(ARTEFACT)/AU/Mindball.component" "$(AU_DIR)/" && \
				echo "Installed: $(AU_DIR)/Mindball.component"; \
			fi ;; \
		Standalone) \
			mkdir -p "$(APP_DIR)" && \
			rm -rf "$(APP_DIR)/Mindball.app" && \
			cp -R "$(ARTEFACT)/Standalone/Mindball.app" "$(APP_DIR)/" && \
			echo "Installed: $(APP_DIR)/Mindball.app" ;; \
		esac; \
	done

clean:
	rm -rf $(BUILD_DIR)
