# Sizzletracker (Android) — build and publish entrypoint.
#
# Every target is atomic and declares its own dependencies, so `make publish`
# alone is enough to go from a clean tree to an APK sitting in the private
# F-Droid repo — and nothing in here runs as a side effect of something else.
#
#   make help              what each target does
#   make check             unit tests + lint (what CI would run)
#   make staging           non-debuggable build for on-device testing
#   make release           unsigned release APK, named for F-Droid
#   make install           adb install the staging APK (keeps app data)
#   make dist              copy the release APK + metadata into dist/
#   make publish           upload dist/ to the F-Droid repo  [MANUAL ONLY]
#   make bump-minor        new feature  -> x.(y+1).0, versionCode +1
#
# Versions come from versions.properties, which Gradle reads too; never edit
# the numbers in app/build.gradle.kts.

SHELL := /bin/sh
GRADLE := ./gradlew
ADB := adb

VERSIONS := versions.properties
APP_ID := $(shell sed -n 's/^[[:space:]]*namespace[[:space:]]*=[[:space:]]*"\(.*\)".*/\1/p' app/build.gradle.kts)
VERSION_NAME := $(shell sed -n 's/^versionName[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ')
VERSION_CODE := $(shell sed -n 's/^versionCode[[:space:]]*=[[:space:]]*//p' $(VERSIONS) | tr -d ' ')

# Publishing to the private F-Droid repo (CLAUDE.md). Both halves of a release
# — the artifact and its metadata — live under the same host.
FDROID_HOST     := rcmd@garage.rcmd.space
FDROID_UNSIGNED := /var/lib/fdroid/unsigned
FDROID_METADATA := /var/lib/fdroid/metadata

# `<application_id>_<version_code>.apk` is the naming scheme the unsigned
# directory expects; app/build.gradle.kts stamps the same name onto the output.
APK_NAME     := $(APP_ID)_$(VERSION_CODE).apk
RELEASE_APK  := app/build/outputs/apk/release/$(APK_NAME)
# R8 renames the release build, so a crash report from it is unreadable without
# this. It is staged beside the APK and kept locally — never published.
RELEASE_MAP  := app/build/outputs/mapping/release/mapping.txt
DIST_MAP     := dist/$(APP_ID)_$(VERSION_CODE)-mapping.txt
STAGING_APK  := app/build/outputs/apk/staging/app-staging.apk
METADATA_YML := dist/$(APP_ID).yml

.DEFAULT_GOAL := help

# ------------------------------------------------------------------ info
help:
	@sed -n 's/^#   //p' Makefile
	@echo ""
	@echo "current: $(APP_ID) $(VERSION_NAME) (versionCode $(VERSION_CODE))"

version:
	@echo "$(VERSION_NAME) $(VERSION_CODE)"

# ------------------------------------------------------------------ deps
# The Android SDK is the one thing we cannot install for the user; fail loudly
# and early rather than letting Gradle produce a confusing error. Gradle itself
# only looks at ANDROID_HOME / ANDROID_SDK_ROOT / local.properties, so when the
# SDK is merely sitting in its default install location we export it here —
# that is the usual case on a fresh macOS checkout.
SDK_DEFAULT := $(HOME)/Library/Android/sdk
ifeq ($(ANDROID_HOME)$(ANDROID_SDK_ROOT),)
ifneq ($(wildcard $(SDK_DEFAULT)/platform-tools),)
export ANDROID_HOME := $(SDK_DEFAULT)
endif
endif

deps:
	@command -v java >/dev/null || { echo "ERROR: JDK 17 required (java not on PATH)"; exit 1; }
	@test -n "$$ANDROID_HOME" -o -n "$$ANDROID_SDK_ROOT" -o -f local.properties || \
	  { echo "ERROR: Android SDK not found — set ANDROID_HOME or write sdk.dir into local.properties"; exit 1; }
	@test -x $(GRADLE) || { echo "ERROR: $(GRADLE) is not executable"; exit 1; }
	@echo "deps ok"

# ------------------------------------------------------------------ verify
test: deps
	$(GRADLE) testDebugUnitTest

lint: deps
	$(GRADLE) lintDebug

check: test lint

# ------------------------------------------------------------------ build
debug: deps
	$(GRADLE) assembleDebug

# Staging is `debug` with debuggability off: ART optimises it, so on-device
# feel matches a real release, but it signs with the debug key and installs
# without a keystore. This is the only build that should ever reach a phone
# during development.
staging: $(STAGING_APK)

$(STAGING_APK): deps
	$(GRADLE) assembleStaging

# Release is deliberately UNSIGNED. The signing key lives only in the private
# F-Droid repo; `fdroid publish` signs what lands in the unsigned directory.
release: $(RELEASE_APK)

$(RELEASE_APK): deps $(VERSIONS)
	$(GRADLE) assembleRelease
	@test -f $@ || { echo "ERROR: expected $@ — versions.properties and the built APK disagree"; exit 1; }

# ------------------------------------------------------------------ device
# -r keeps the app's data (projects, presets, themes, bindings) across installs.
install: $(STAGING_APK)
	$(ADB) install -r $(STAGING_APK)

launch:
	$(ADB) shell monkey -p $(APP_ID) -c android.intent.category.LAUNCHER 1

# ------------------------------------------------------------------ dist
# Everything a publish needs, staged locally first so it can be inspected
# before anything leaves the machine.
dist: dist/$(APK_NAME) $(DIST_MAP) $(METADATA_YML)

dist/$(APK_NAME): $(RELEASE_APK)
	@mkdir -p dist
	cp $(RELEASE_APK) $@

# The de-obfuscation map for this exact versionCode. `publish` does not upload it;
# it stays here so a stack trace from the published APK can still be read.
$(DIST_MAP): $(RELEASE_APK)
	@mkdir -p dist
	cp $(RELEASE_MAP) $@

# F-Droid metadata. Regenerated from versions.properties on every dist so the
# CurrentVersion lines can never lag the APK next to them.
$(METADATA_YML): $(VERSIONS) Makefile
	@mkdir -p dist
	@printf '%s\n' \
	  'Categories:' \
	  '  - Multimedia' \
	  'License: GPL-3.0-or-later' \
	  'SourceCode: https://git.rcmd.space/tiredsysadmin/sizzletracker-android' \
	  'IssueTracker: https://git.rcmd.space/tiredsysadmin/sizzletracker-android/issues' \
	  'Donate: https://rcmd.space/pages/support/' \
	  '' \
	  'AutoName: Sizzletracker' \
	  'Summary: Retro grid-based music tracker' \
	  '' \
	  'Description: |-' \
	  '    A retro, grid-based music tracker: monospace UI, pattern editing, a' \
	  '    4-track mixer with instruments and effects, and master recording.' \
	  '    Playable with touch, keyboard, gamepad and MIDI (USB or Bluetooth).' \
	  '' \
	  'CurrentVersion: $(VERSION_NAME)' \
	  'CurrentVersionCode: $(VERSION_CODE)' > $@
	@echo "wrote $@"

# ------------------------------------------------------------------ publish
#
# MANUAL ONLY (CLAUDE.md): publishing is never a side effect of a build, never
# wired into a test or release target, and never run unattended. Each half is
# its own target so a metadata fix does not re-upload an APK, and vice versa.
publish-apk: dist/$(APK_NAME)
	scp dist/$(APK_NAME) $(FDROID_HOST):$(FDROID_UNSIGNED)/$(APK_NAME)

publish-metadata: $(METADATA_YML)
	scp $(METADATA_YML) $(FDROID_HOST):$(FDROID_METADATA)/$(APP_ID).yml

publish: publish-apk publish-metadata
	@echo "published $(APP_ID) $(VERSION_NAME) ($(VERSION_CODE)); sign it on the repo host"
	@echo "keep $(DIST_MAP) — it is the only way to read a crash from this build"

# ------------------------------------------------------------------ versioning
# versionCode always moves by exactly 1: F-Droid and the package manager order
# installs by it alone, and a skipped or reused code is not recoverable.
bump-major: ; @$(MAKE) --no-print-directory bump FIELD=1
bump-minor: ; @$(MAKE) --no-print-directory bump FIELD=2
bump-patch: ; @$(MAKE) --no-print-directory bump FIELD=3

bump:
	@awk -v field=$(FIELD) ' \
	  /^versionName/ { \
	    split($$3, v, "."); \
	    v[field]++; \
	    for (i = field + 1; i <= 3; i++) v[i] = 0; \
	    printf "versionName = %d.%d.%d\n", v[1], v[2], v[3]; next } \
	  /^versionCode/ { printf "versionCode = %d\n", $$3 + 1; next } \
	  { print }' $(VERSIONS) > $(VERSIONS).tmp
	@mv $(VERSIONS).tmp $(VERSIONS)
	@grep -E '^version(Name|Code)' $(VERSIONS) | sed 's/^/  /'

# ------------------------------------------------------------------ clean
clean:
	$(GRADLE) clean
	rm -rf dist

.PHONY: help version deps test lint check debug staging release install launch \
        dist publish publish-apk publish-metadata bump bump-major bump-minor \
        bump-patch clean
