APP_NAME   := Wakeful
BUNDLE_ID  := com.github.wakeful.Wakeful
VERSION    := 1.1.0

# Override with: make SIGN_ID="Developer ID Application: Your Name (TEAMID)"
SIGN_ID    ?= -

# ?= so `bundle` can be re-invoked with a different source directory.
BUILD_DIR     ?= .build/release
UNIVERSAL_DIR := .build/apple/Products/Release
DIST          := dist
APP           := $(DIST)/$(APP_NAME).app
CONTENTS      := $(APP)/Contents

# A secure timestamp is required for notarization but impossible for ad-hoc.
TS := $(if $(filter -,$(SIGN_ID)),--timestamp=none,--timestamp)

.PHONY: all build universal app app-universal bundle sign install uninstall run check clean

all: app

## Build for this Mac's architecture only (fast).
build:
	swift build -c release

## Build a universal (arm64 + x86_64) binary. Note SwiftPM writes multi-arch
## builds to a different directory, which is why `bundle` is parameterised.
universal:
	swift build -c release --arch arm64 --arch x86_64

## Assemble and sign Wakeful.app into ./dist
app: build bundle

## Same, from a universal binary.
app-universal: universal
	$(MAKE) bundle BUILD_DIR=$(UNIVERSAL_DIR)

bundle:
	rm -rf "$(APP)"
	mkdir -p "$(CONTENTS)/MacOS" "$(CONTENTS)/Resources"
	cp "$(BUILD_DIR)/$(APP_NAME)" "$(CONTENTS)/MacOS/$(APP_NAME)"
	sed -e 's|__BUNDLE_ID__|$(BUNDLE_ID)|g' \
	    -e 's|__VERSION__|$(VERSION)|g' \
	    Resources/Info.plist > "$(CONTENTS)/Info.plist"
	printf 'APPL????' > "$(CONTENTS)/PkgInfo"
	$(MAKE) sign
	@echo ""
	@echo "Built $(APP)"
	@echo "Run 'make install' to copy it to /Applications and launch it."

## Code-sign the bundle. Ad-hoc by default; pass SIGN_ID for a real identity.
sign:
	codesign --force --options runtime $(TS) --sign "$(SIGN_ID)" "$(APP)"
	codesign --verify --verbose=2 "$(APP)"

## Install to /Applications and launch. Login-item registration needs the app
## to live in a stable location, so install before enabling Launch at Login.
install: app
	- osascript -e 'quit app "$(APP_NAME)"' 2>/dev/null || true
	rm -rf "/Applications/$(APP_NAME).app"
	cp -R "$(APP)" /Applications/
	open "/Applications/$(APP_NAME).app"

uninstall:
	- osascript -e 'quit app "$(APP_NAME)"' 2>/dev/null || true
	rm -rf "/Applications/$(APP_NAME).app"
	defaults delete $(BUNDLE_ID) 2>/dev/null || true
	@echo "Removed. If Launch at Login was on, also check"
	@echo "System Settings > General > Login Items & Extensions."

## Run the built binary straight from the terminal (for debugging).
## Note: Preferences and Launch at Login only behave correctly in the .app bundle.
run: build
	"$(BUILD_DIR)/$(APP_NAME)"

## The same basic checks CI runs (syntax, Info.plist, version, whitespace).
check:
	scripts/check.sh

clean:
	swift package clean
	rm -rf .build "$(DIST)"
