# SuperSay build. `make` builds a release .app into build/, `make run` launches it,
# `make dist` builds the copy that goes to testers (see below).
SHELL    := /bin/bash
.SHELLFLAGS := -o pipefail -c
APP      := SuperSay
BUNDLE   := build/$(APP).app
CONFIG   ?= release
ENTITLEMENTS := Packaging/$(APP).entitlements
VERSION  := $(shell /usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' Packaging/Info.plist)

# Signing: ad-hoc, with an identifier-based designated requirement so macOS keeps the
# Microphone and Accessibility grants across rebuilds (a bare ad-hoc identity changes on every
# build). Ad-hoc builds skip the hardened runtime. If an Apple Development or "SuperSay Dev"
# certificate is in the keychain it is used instead.
SIGN_ID  ?= $(shell security find-identity -v -p codesigning 2>/dev/null | grep -oE '"(SuperSay Dev|Apple Development[^"]*)"' | head -1 | tr -d '"')
ifeq ($(SIGN_ID),)
SIGN_ID  := -
endif

# The tester build is compiled with its scratch folder in a neutral place: SwiftPM writes that
# path into the binary (for its resource bundles), and the repo sits under a personal folder.
DIST_SCRATCH := /private/tmp/supersay-scratch/.build
DIST_DIR     := dist
# Anything matching this in the tester build stops `make dist` (add your own names in a
# local, untracked PERSONAL override: `make dist PERSONAL="a|b|c"`).
PERSONAL     ?= adityamohite|claude code|Aditya|Mohite

.PHONY: all build app run debug clean icon dist keys code release site notes smoke

all: app

build:
	swift build -c $(CONFIG) $(SCRATCH_FLAG) 2>&1 | tail -20

app: build
	@rm -rf $(BUNDLE)
	@mkdir -p build && touch build/.metadata_never_index   # keeps Spotlight and Launchpad from listing build copies of the app
	@mkdir -p $(BUNDLE)/Contents/MacOS $(BUNDLE)/Contents/Resources $(BUNDLE)/Contents/Frameworks
	@cp $(PRODUCTS)/$(APP) $(BUNDLE)/Contents/MacOS/$(APP)
	@cp Packaging/Info.plist $(BUNDLE)/Contents/Info.plist
	@# SPM resource bundles sit next to the binary; ship only those of current targets.
	@for b in $(PRODUCTS)/*.bundle; do \
	  [ -d "$$b" ] || continue; \
	  name=$$(basename "$$b" | cut -d_ -f1); \
	  grep -q "name: \"$$name\"" Package.swift && cp -R "$$b" $(BUNDLE)/Contents/Resources/ || echo "skipping stale $$b"; \
	done
	@[ -f Packaging/AppIcon.icns ] && cp Packaging/AppIcon.icns $(BUNDLE)/Contents/Resources/ || true
	@# Sparkle (the updater) is a dynamic framework; embed it where the rpath expects it. Its XPC
	@# services only matter for sandboxed apps, so they stay out of the bundle.
	@cp -R $(SPARKLE)/Sparkle.xcframework/macos-arm64_x86_64/Sparkle.framework $(BUNDLE)/Contents/Frameworks/
	@rm -rf $(BUNDLE)/Contents/Frameworks/Sparkle.framework/Versions/B/XPCServices
	@$(MAKE) --no-print-directory sign IDENTITY="$(SIGN_ID)"
	@echo "→ $(BUNDLE)  (signed: $(SIGN_ID))"

PRODUCTS = .build/$(CONFIG)
SPARKLE   = $(dir $(PRODUCTS))artifacts/sparkle/Sparkle

# Inside-out signing: Sparkle's nested helpers first, then the framework, then the app. Ad-hoc builds
# skip the hardened runtime on the app (its library validation refuses an ad-hoc framework).
sign:
	@F=$(BUNDLE)/Contents/Frameworks/Sparkle.framework; \
	 codesign -f -s "$(IDENTITY)" -o runtime $$F/Versions/B/Autoupdate 2>&1 | grep -v "replacing existing" || true; \
	 codesign -f -s "$(IDENTITY)" -o runtime $$F/Versions/B/Updater.app 2>&1 | grep -v "replacing existing" || true; \
	 codesign -f -s "$(IDENTITY)" -o runtime $$F 2>&1 | grep -v "replacing existing" || true
	@if [ "$(IDENTITY)" = "-" ]; then \
	  codesign -f -s - --entitlements $(ENTITLEMENTS) \
	    --requirements '=designated => identifier "com.supertoolslabs.supersay"' $(BUNDLE) 2>&1 | grep -v "replacing existing" || true; \
	else \
	  codesign -f -s "$(IDENTITY)" -o runtime --timestamp --entitlements $(ENTITLEMENTS) $(BUNDLE) 2>&1 | grep -v "replacing existing" || true; \
	fi
	@codesign --verify --deep --strict $(BUNDLE) && echo "signature verified" || echo "WARNING: signature invalid"

run: app
	@pkill -x $(APP) 2>/dev/null || true
	@open $(BUNDLE)

debug:
	@$(MAKE) CONFIG=debug run

clean:
	rm -rf .build build dist

# The build that leaves this Mac: compiled with a neutral scratch path, then checked for
# anything personal before it is zipped. Fails (and writes no zip) if the check finds a name.
# The zip is what you send; the source zip beside it is what the GPL asks you to give with it.
dist:
	@$(MAKE) --no-print-directory app SCRATCH_FLAG="--scratch-path $(DIST_SCRATCH) -Xswiftc -DSUPERSAY_DIST" PRODUCTS="$(DIST_SCRATCH)/$(CONFIG)"
	@if strings $(BUNDLE)/Contents/MacOS/$(APP) | grep -q -i -E "$(PERSONAL)"; then \
	  echo "FAIL: the binary contains a personal name or path:"; strings $(BUNDLE)/Contents/MacOS/$(APP) | grep -i -E "$(PERSONAL)" | head; exit 1; fi
	@if grep -r -l -i -E "$(PERSONAL)" $(BUNDLE)/Contents/Info.plist $(BUNDLE)/Contents/Resources/*.bundle >/dev/null 2>&1; then \
	  echo "FAIL: a personal name is in the bundle resources"; exit 1; fi
	@rm -rf $(DIST_DIR) && mkdir -p "$(DIST_DIR)/stage/$(APP) $(VERSION)"
	@touch $(DIST_DIR)/.metadata_never_index
	@cp -R $(BUNDLE) "$(DIST_DIR)/stage/$(APP) $(VERSION)/"
	@git archive --format=zip --prefix=$(APP)-$(VERSION)-source/ -o "$(DIST_DIR)/stage/$(APP) $(VERSION)/Source code (GPL v3).zip" HEAD
	@cp Packaging/INSTALL.txt "$(DIST_DIR)/stage/$(APP) $(VERSION)/Read me first.txt"
	@cd $(DIST_DIR)/stage && ditto -c -k --norsrc --noextattr --keepParent "$(APP) $(VERSION)" ../$(APP)-$(VERSION).zip
	@rm -rf $(DIST_DIR)/stage
	@echo "→ $(DIST_DIR)/$(APP)-$(VERSION).zip  (the app, its source code and a read-me, in one zip; clean)"

# Regenerate Packaging/AppIcon.icns from Tools/icon.swift.
icon:
	@rm -rf build/AppIcon.iconset && mkdir -p build/AppIcon.iconset
	@swift Tools/icon.swift build/AppIcon.iconset
	@cd build/AppIcon.iconset && for s in 16 32 128 256 512; do \
	   cp icon_$$s.png icon_$${s}x$${s}.png; d=$$((s*2)); cp icon_$$d.png icon_$${s}x$${s}@2x.png; done && rm icon_16.png icon_32.png icon_64.png icon_128.png icon_256.png icon_512.png icon_1024.png
	@iconutil -c icns build/AppIcon.iconset -o Packaging/AppIcon.icns && echo "→ Packaging/AppIcon.icns"

# Extension codes. `make keys` once (prints the public key for TrialCode.swift), then
# `make code ID=A1B2-C3D4-E5F6-0718 DAYS=7` for each tester who needs more time.
TRIALTOOL := build/trialtool
$(TRIALTOOL): Tools/trialtool/main.swift Sources/SuperSay/Support/TrialCode.swift
	@mkdir -p build && swiftc -O -o $@ Tools/trialtool/main.swift Sources/SuperSay/Support/TrialCode.swift 2>&1 | grep -v warning || true

keys: $(TRIALTOOL)
	@$(TRIALTOOL) keygen

code: $(TRIALTOOL)
	@$(TRIALTOOL) issue "$(ID)" $(DAYS)

# ---- Updates (Sparkle) -------------------------------------------------------------------------
# One-time: `make updatekeys` creates ~/.supersay/update-signing.key (back it up) and prints the public
# key that Packaging/Info.plist carries as SUPublicEDKey. Per release: bump CFBundleShortVersionString and
# CFBundleVersion (a whole number that only goes up) in Packaging/Info.plist, add a CHANGELOG entry, then
# `make site`. That writes the tester zip, the signed update archive and the appcast into the website
# folder; upload the website zip to Netlify to publish.
SITE_DIR   ?= ../supersay-site
UPDATE_KEY ?= $(HOME)/.supersay/update-signing.key
UPDATE_URL ?= https://supersay.app/updates/
SPARKLE_BIN := .build/artifacts/sparkle/Sparkle/bin

updatekeys:
	@swift Tools/updatekeys.swift

# Release notes for the update window: the top CHANGELOG.md entry as a small HTML page.
notes:
	@mkdir -p $(DIST_DIR)
	@python3 -c 'import re,html; t=open("CHANGELOG.md").read(); m=re.search(r"^## (.+?)\n(.*?)(?=^## |\Z)", t, re.S|re.M); title,body=m.group(1),m.group(2).strip(); items=[html.escape(re.sub(r"\s+"," ",i.strip())) for i in re.split(r"^- ", body, flags=re.M)[1:]]; print("<!doctype html><meta charset=utf-8><style>body{font:14px/1.5 -apple-system,system-ui;color:#222;margin:16px 20px}h1{font-size:17px;margin:0 0 8px}li{margin:4px 0}@media(prefers-color-scheme:dark){body{color:#ddd;background:#1e1e1e}}</style><h1>SuperSay "+html.escape(title)+"</h1><ul>"+"".join("<li>"+i+"</li>" for i in items)+"</ul>")' > $(DIST_DIR)/$(APP)-$(VERSION).html

# Launch test for the tester build, the way a stranger's Mac would run it: the app copied to a fresh place
# and the folder it was compiled in moved away. It must still be running after 8 seconds and leave no
# crash report. (An earlier build found its word lists only through that folder, and crashed on launch.)
smoke:
	@set -e; T=$$(mktemp -d); cp -R $(BUNDLE) $$T/; \
	 [ -d $(DIST_SCRATCH) ] && mv $(DIST_SCRATCH) $(DIST_SCRATCH).away || true; \
	 trap '[ -d $(DIST_SCRATCH).away ] && mv $(DIST_SCRATCH).away $(DIST_SCRATCH); rm -rf $$T' EXIT; \
	 before=$$(ls ~/Library/Logs/DiagnosticReports 2>/dev/null | grep -c "^$(APP)" || true); \
	 SUPERSAY_SMOKE=1 $$T/$(APP).app/Contents/MacOS/$(APP) >/dev/null 2>&1 & pid=$$!; sleep 8; \
	 if kill -0 $$pid 2>/dev/null; then echo "smoke test passed: still running after 8 s, build folder absent"; kill $$pid; else echo "SMOKE TEST FAILED: the app died within 8 s"; exit 1; fi; \
	 after=$$(ls ~/Library/Logs/DiagnosticReports 2>/dev/null | grep -c "^$(APP)" || true); \
	 [ "$$after" = "$$before" ] || { echo "SMOKE TEST FAILED: a crash report appeared"; exit 1; }

release: dist
	@$(MAKE) --no-print-directory smoke
	@$(MAKE) --no-print-directory notes
	@test -f "$(UPDATE_KEY)" || { echo "No update key: run 'make updatekeys' first"; exit 1; }
	@mkdir -p $(DIST_DIR)/updates
	@ditto -c -k --norsrc --noextattr --keepParent $(BUNDLE) $(DIST_DIR)/updates/$(APP)-$(VERSION).zip
	@cp $(DIST_DIR)/$(APP)-$(VERSION).html $(DIST_DIR)/updates/
	@$(SPARKLE_BIN)/generate_appcast --ed-key-file "$(UPDATE_KEY)" --download-url-prefix "$(UPDATE_URL)" --embed-release-notes --maximum-versions 1 --maximum-deltas 0 -o $(DIST_DIR)/appcast.xml $(DIST_DIR)/updates/ >/dev/null
	@rm -f $(DIST_DIR)/updates/*.html $(DIST_DIR)/updates/*.delta
	@echo "→ $(DIST_DIR)/updates/$(APP)-$(VERSION).zip and $(DIST_DIR)/appcast.xml (signed)"

# Copy the release into the website folder. This does not publish: upload the website zip to Netlify.
site: release
	@mkdir -p $(SITE_DIR)/updates $(SITE_DIR)/downloads
	@rm -f $(SITE_DIR)/updates/*.zip $(SITE_DIR)/downloads/*.zip
	@cp $(DIST_DIR)/updates/$(APP)-$(VERSION).zip $(SITE_DIR)/updates/
	@cp $(DIST_DIR)/appcast.xml $(SITE_DIR)/appcast.xml
	@cp $(DIST_DIR)/$(APP)-$(VERSION).zip $(SITE_DIR)/downloads/$(APP).zip
	@echo "→ $(SITE_DIR): appcast.xml, updates/$(APP)-$(VERSION).zip, downloads/$(APP).zip"
