CMAKE       ?= cmake
CONFIG      ?= Release
BUILD_DIR   ?= build
JOBS        ?= $(shell sysctl -n hw.availcpu 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 8)
CC          ?= cc

ART_DIR     := $(BUILD_DIR)/Pascalcompressor_artefacts/$(CONFIG)
GEN_DIR     := $(BUILD_DIR)/generated
GEN_H       := $(GEN_DIR)/BuildInfo.h

VST3_SRC    := $(ART_DIR)/VST3/Pascalcompressor.vst3
AU_SRC      := $(ART_DIR)/AU/Pascalcompressor.component

VST3_DEST   := $(HOME)/Library/Audio/Plug-Ins/VST3/Pascalcompressor.vst3
AU_DEST     := $(HOME)/Library/Audio/Plug-Ins/Components/Pascalcompressor.component

AU_BIN      := $(AU_DEST)/Contents/MacOS/Pascalcompressor
AUTEST_BIN  := $(BUILD_DIR)/autest

PLUGIN_DIRS := $(dir $(VST3_DEST)) $(dir $(AU_DEST))
AU_CODE     := aufx Pscp PscC

MAKEFLAGS += --no-print-directory

.PHONY: all build configure install uninstall clean smoke auval FORCE

all: build

configure:
	$(CMAKE) -S . -B $(BUILD_DIR) -DCMAKE_BUILD_TYPE=$(CONFIG)

FORCE:

$(GEN_H): FORCE
	@mkdir -p "$(GEN_DIR)"
	@printf '#pragma once\n#define PASCAL_BUILD_TIME "%s"\n' "$$(date '+%Y-%m-%d %H:%M:%S %Z')" > "$(GEN_H)"

build: configure $(GEN_H)
	$(CMAKE) --build $(BUILD_DIR) --config $(CONFIG) --parallel $(JOBS)
	@printf 'built at %s (local)\n' "$$(sed -n 's/^#define PASCAL_BUILD_TIME "\(.*\)"/\1/p' "$(GEN_H)")"

$(AUTEST_BIN): Tests/autest.c
	@mkdir -p "$(BUILD_DIR)"
	$(CC) -O2 -framework AudioToolbox -framework CoreFoundation -o "$(AUTEST_BIN)" Tests/autest.c

smoke: $(AUTEST_BIN)
	@if [ -e "$(AU_SRC)/Contents/MacOS/Pascalcompressor" ]; then \
		"$(AUTEST_BIN)" "$(AU_SRC)/Contents/MacOS/Pascalcompressor"; \
	elif [ -e "$(AU_BIN)" ]; then \
		"$(AUTEST_BIN)" "$(AU_BIN)"; \
	else \
		echo "Nothing to test yet: run 'make build' or 'make install' first."; \
		exit 1; \
	fi

install: build
	@rm -rf "$(VST3_DEST)" "$(AU_DEST)"
	@mkdir -p $(PLUGIN_DIRS)
	@cp -R "$(VST3_SRC)" "$(VST3_DEST)"
	@cp -R "$(AU_SRC)" "$(AU_DEST)"
	@chmod -R a+rX "$(VST3_DEST)" "$(AU_DEST)"
	@xattr -cr "$(VST3_DEST)" "$(AU_DEST)"
	@codesign --force --sign - "$(VST3_DEST)" "$(AU_DEST)"
	@codesign -dv "$(VST3_DEST)" 2>&1 | head -2
	@echo ""
	@echo "Pascalcompressor installed to:"
	@echo "  $(VST3_DEST)"
	@echo "  $(AU_DEST)"
	@echo ""
	@$(MAKE) smoke

auval:
	@if auval -v $(AU_CODE) 2>&1 | grep -q "PASS\|* *NOT OK\|FAIL\|didn't find"; then \
		auval -v $(AU_CODE) 2>&1 | tail -20; \
		if auval -l $(AU_CODE) 2>/dev/null | grep -q Pscp; then \
			echo "AU validation PASSED."; \
		else \
			echo "auval did not find the component yet. The stock AudioUnit Registrar only scans"; \
			echo "for new .component bundles at logout/login (or reboot); this is a machine-wide"; \
			echo "state, not a plugin problem. The functional check already passed: run 'make smoke'."; \
		fi; \
	fi

uninstall:
	@rm -rf "$(VST3_DEST)" "$(AU_DEST)"
	@echo "Pascalcompressor uninstalled."

clean:
	$(CMAKE) -E remove_directory $(BUILD_DIR)