.DEFAULT_GOAL := help

# Public Navidrome demo server, used by test-live and shots.
DEMO_URL  ?= https://demo.navidrome.org
DEMO_USER ?= demo
DEMO_PASS ?= demo

# Scratch config and cache for scripted runs, so they never touch your own.
SHOTS_DIR := target/shots
SCRATCH   := target/scratch

FLATPAK_ID      := me.anshorei.Fettleshed.Remus
FLATPAK_DIR     := target/flatpak
FLATPAK_SDK     := org.freedesktop.Sdk//26.08
FLATPAK_BUILDER := $(shell command -v flatpak-builder 2>/dev/null || echo flatpak run org.flatpak.Builder)

.PHONY: help
help: ## List the targets
	@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-16s\033[0m %s\n", $$1, $$2}'

.PHONY: build
build: ## Debug build
	cargo build

.PHONY: release
release: ## Optimised build, binary in target/release/remus
	cargo build --release

.PHONY: run
run: ## Run fullscreen
	cargo run --release

.PHONY: run-windowed
run-windowed: ## Run in a window
	cargo run --release -- --windowed

.PHONY: fmt
fmt: ## Format the code
	cargo fmt

.PHONY: fmt-check
fmt-check: ## Fail if the code is not formatted
	cargo fmt --check

.PHONY: lint
lint: ## Clippy, warnings as errors
	cargo clippy --all-targets -- -D warnings

.PHONY: test
test: ## Unit tests
	cargo test

.PHONY: check
check: fmt-check lint test ## Formatting, lint and tests: run before committing

.PHONY: test-live
test-live: ## Every Subsonic call against a real server (DEMO_URL, DEMO_USER, DEMO_PASS)
	REMUS_TEST_URL=$(DEMO_URL) REMUS_TEST_USER=$(DEMO_USER) REMUS_TEST_PASS=$(DEMO_PASS) \
		cargo test live_server -- --ignored --nocapture

.PHONY: shots
shots: ## Screenshot the main screens against the demo server into target/shots
	@mkdir -p $(SHOTS_DIR) $(SCRATCH)/config/remus $(SCRATCH)/cache
	@salt=$$(head -c 8 /dev/urandom | od -An -tx1 | tr -d ' \n'); \
	token=$$(printf '%s%s' '$(DEMO_PASS)' "$$salt" | md5sum | cut -d' ' -f1); \
	printf 'url = "%s"\nusername = "%s"\nsalt = "%s"\ntoken = "%s"\n' \
		'$(DEMO_URL)' '$(DEMO_USER)' "$$salt" "$$token" > $(SCRATCH)/config/remus/config.toml
	cargo build
	XDG_CONFIG_HOME=$(CURDIR)/$(SCRATCH)/config XDG_CACHE_HOME=$(CURDIR)/$(SCRATCH)/cache \
	REMUS_DEV_SCRIPT="wait:4000,shot:$(SHOTS_DIR)/home.png,right,activate,wait:3000,shot:$(SHOTS_DIR)/album.png,down,activate,wait:3000,now-playing,wait:2500,shot:$(SHOTS_DIR)/now-playing.png,play-pause,back,section-next,section-next,section-next,wait:3000,shot:$(SHOTS_DIR)/artists.png,quit" \
		./target/debug/remus

.PHONY: sdk-check
sdk-check: ## make check inside the Flatpak SDK, which has the GStreamer dev files
	flatpak run --share=network --filesystem=$(CURDIR) --command=sh $(FLATPAK_SDK) -c '\
		export PATH=$$PATH:/usr/lib/sdk/rust-stable/bin CARGO_HOME=$(CURDIR)/target/sdk/cargo-home \
			CARGO_TARGET_DIR=$(CURDIR)/target/sdk REMUS_AUDIO_SINK=fakesink && \
		cd $(CURDIR) && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test'

.PHONY: flatpak
flatpak: ## Build the Flatpak into target/flatpak/repo
	cargo vendor --locked $(FLATPAK_DIR)/vendor > /dev/null
	$(FLATPAK_BUILDER) --user --install-deps-from=flathub --force-clean --state-dir=$(FLATPAK_DIR)/state \
		--repo=$(FLATPAK_DIR)/repo $(FLATPAK_DIR)/build flatpak/$(FLATPAK_ID).yml

.PHONY: flatpak-install
flatpak-install: flatpak ## Build the Flatpak and install it for this user
	flatpak --user remote-add --if-not-exists --no-gpg-verify remus-local $(FLATPAK_DIR)/repo
	flatpak --user install -y --reinstall remus-local $(FLATPAK_ID)

.PHONY: flatpak-bundle
flatpak-bundle: flatpak ## Build target/flatpak/remus.flatpak, a single file to copy to a Steam machine
	flatpak build-bundle --runtime-repo=https://dl.flathub.org/repo/flathub.flatpakrepo \
		$(FLATPAK_DIR)/repo $(FLATPAK_DIR)/remus.flatpak $(FLATPAK_ID)

.PHONY: branding
branding: ## Regenerate the logo SVGs and render the PNGs (needs inkscape)
	python3 branding/generate.py
	@mkdir -p branding/png
	@render() { inkscape "branding/svg/$$1.svg" -w $$2 -h $$3 -o "branding/png/$$4.png" 2>/dev/null; }; \
	render remus-square 1024 1024 remus-square-1024; \
	for s in 512 256 128 64 32; do render remus-icon $$s $$s remus-icon-$$s; done; \
	for v in remus-logo remus-logo-maroon remus-logo-stacked remus-logo-stacked-maroon; do \
		inkscape "branding/svg/$$v.svg" -h 480 -o "branding/png/$$v.png" 2>/dev/null; done; \
	render steam-capsule-portrait 600 900 steam-capsule-portrait-600x900; \
	render steam-capsule-wide 920 430 steam-capsule-wide-920x430; \
	render steam-hero 3840 1240 steam-hero-3840x1240; \
	render steam-logo 1280 720 steam-logo-1280x720; \
	render steam-icon 256 256 steam-icon-256

# Versioning. Cargo.toml's [package] version is the one source: the app shows
# it, and the bump writes it to Cargo.lock and the Flatpak metainfo too.
PACKAGE  = $(shell awk -F'"' '/^\[package\]/{p=1;next} /^\[/{p=0} p && /^name *= *"/{print $$2; exit}' Cargo.toml)
CURRENT  = $(shell awk -F'"' '/^\[package\]/{p=1;next} /^\[/{p=0} p && /^version *= *"/{print $$2; exit}' Cargo.toml)
METAINFO = flatpak/$(FLATPAK_ID).metainfo.xml

.PHONY: version
version: ## Print the current version
	@echo $(CURRENT)

patch: BUMP = patch
minor: BUMP = minor
major: BUMP = major

.PHONY: patch minor major
patch: bump ## Bump for a bug fix: amend into the last commit and tag it
minor: bump ## Bump for a feature: amend into the last commit and tag it
major: bump ## Bump for a breaking change, decided by hand

# Folds the bump into the last commit and tags it, as one action, so there is
# never a bump without a tag or a tag without a bump. Refuses anything that
# would make rewriting that commit lose work, orphan a tag or need a force push,
# and a version CHANGELOG.md does not describe yet.
.PHONY: bump
bump:
	@set -e; \
	if [ -z "$(BUMP)" ]; then echo "error: run make patch, make minor or make major" >&2; exit 1; fi; \
	if ! git rev-parse -q --verify HEAD >/dev/null 2>&1; then \
		echo "error: no commits yet, so there is no commit to fold a version bump into. Commit first." >&2; \
		exit 1; \
	fi; \
	if [ -n "$$(git status --porcelain)" ]; then \
		echo "error: working tree is dirty. Commit or stash first, and decide whether that work belongs in this version:" >&2; \
		git status --short >&2; \
		exit 1; \
	fi; \
	if [ -n "$$(git tag --points-at HEAD)" ]; then \
		echo "error: HEAD is already tagged $$(git tag --points-at HEAD | paste -sd' '). Amending it would leave that tag on an orphaned commit. Commit something first." >&2; \
		exit 1; \
	fi; \
	if upstream=$$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null) && \
	   git merge-base --is-ancestor HEAD "$$upstream" 2>/dev/null; then \
		echo "error: HEAD is already pushed to $$upstream. Amending it would need a force push. Commit something first." >&2; \
		exit 1; \
	fi; \
	current="$(CURRENT)"; \
	if [ -z "$$current" ]; then echo "error: no version found in the [package] table of Cargo.toml" >&2; exit 1; fi; \
	new=$$(echo "$$current" | awk -F. -v kind=$(BUMP) '{ \
		if (NF != 3) exit 1; \
		if (kind == "patch") printf "%d.%d.%d\n", $$1, $$2, $$3 + 1; \
		else if (kind == "minor") printf "%d.%d.0\n", $$1, $$2 + 1; \
		else printf "%d.0.0\n", $$1 + 1 }'); \
	if [ -z "$$new" ]; then echo "error: cannot bump version '$$current': expected major.minor.patch" >&2; exit 1; fi; \
	if git rev-parse -q --verify "refs/tags/v$$new" >/dev/null; then \
		echo "error: tag v$$new already exists" >&2; exit 1; \
	fi; \
	if ! grep -q "^## v$$new " CHANGELOG.md 2>/dev/null; then \
		echo "error: CHANGELOG.md has no '## v$$new' entry. Add one to the last commit first (git commit --amend)." >&2; \
		exit 1; \
	fi; \
	today=$$(date +%Y-%m-%d); \
	awk -v v="$$new" '/^\[package\]/{p=1} /^\[/ && !/^\[package\]/{p=0} p && /^version *= *"/{sub(/"[^"]*"/, "\"" v "\"")} {print}' Cargo.toml > Cargo.toml.bump; \
	mv Cargo.toml.bump Cargo.toml; \
	awk -v v="$$new" -v pkg="$(PACKAGE)" '$$0 == "name = \"" pkg "\""{f=1} f && /^version = "/{sub(/"[^"]*"/, "\"" v "\""); f=0} {print}' Cargo.lock > Cargo.lock.bump; \
	mv Cargo.lock.bump Cargo.lock; \
	awk -v v="$$new" -v d="$$today" '{print} /^ *<releases>/{print "    <release version=\"" v "\" date=\"" d "\"/>"}' $(METAINFO) > $(METAINFO).bump; \
	mv $(METAINFO).bump $(METAINFO); \
	git add Cargo.toml Cargo.lock $(METAINFO); \
	git commit --quiet --amend --no-edit; \
	git tag -a "v$$new" -m "v$$new"; \
	echo "$$current -> $$new, tagged v$$new on $$(git rev-parse --short HEAD) ($$(git log -1 --format=%s))"

.PHONY: clean
clean: ## Remove build output, screenshots and scratch config
	cargo clean
