APP_NAME   := LuxeNotifier
BUILD_DIR  := .build/release-bundle
APP_BUNDLE := $(BUILD_DIR)/$(APP_NAME).app
BIN_DIR    := $(HOME)/.local/bin
APPS_DIR   := $(HOME)/Applications

.PHONY: build bundle install uninstall test

build:
	swift build -c release

# Notifications and launch-at-login only work from a real bundle, so ad-hoc sign one.
bundle: build
	rm -rf $(APP_BUNDLE)
	mkdir -p $(APP_BUNDLE)/Contents/MacOS
	cp Resources/Info.plist $(APP_BUNDLE)/Contents/Info.plist
	cp "$$(swift build -c release --show-bin-path)/$(APP_NAME)" $(APP_BUNDLE)/Contents/MacOS/$(APP_NAME)
	codesign --force --sign - $(APP_BUNDLE)

install: bundle
	mkdir -p $(BIN_DIR) $(APPS_DIR)
	cp "$$(swift build -c release --show-bin-path)/luxe-notify" $(BIN_DIR)/luxe-notify
	rm -rf $(APPS_DIR)/$(APP_NAME).app
	cp -R $(APP_BUNDLE) $(APPS_DIR)/$(APP_NAME).app
	@echo "Installed. Open it with: open $(APPS_DIR)/$(APP_NAME).app"

uninstall:
	-pkill $(APP_NAME)
	rm -f $(BIN_DIR)/luxe-notify
	rm -rf $(APPS_DIR)/$(APP_NAME).app
	rm -rf "$(HOME)/Library/Application Support/LuxeNotifier"

# The first test build after a change sometimes fails with "plugin for module 'TestingMacros' not
# found" under Command Line Tools (no Xcode) and passes on an immediate retry. Cause not found; this
# retries once and only when that exact error appears, so real failures still fail.
test:
	@swift test 2>&1 | tee .build/last-test.log | grep -v -E '^\[[0-9]+ / [0-9]+\]'; \
	status=$${PIPESTATUS[0]}; \
	if [ $$status -ne 0 ] && grep -q "plugin for module 'TestingMacros' not found" .build/last-test.log; then \
		echo "retrying once: known TestingMacros first-build error"; swift test; \
	else exit $$status; fi
