#
# RFGuard - passive BLE / WiFi surveillance-equipment detector
# C (gnu17) + Allegro 5 + Nilorea N_GUI. Linux desktop, Raspberry Pi, Android.
#
# Based on Wardrive Go by RocketGod (GPL-3.0, the original work),
# https://github.com/RocketGod-git/wardrive-go
#
# Usage:
#   make                  native Linux / Raspberry Pi binary (./rfguard)
#   make DEBUG=1          ASan + UBSan build into obj-asan/ (./rfguard-asan)
#   make test             build and run every unit test in tests/ (ASan + UBSan)
#   make check            cppcheck over src/ (gating)
#   make install          FHS install (PREFIX=/usr/local, honours DESTDIR)
#   make setcap           give the binary CAP_NET_RAW + CAP_NET_ADMIN (BLE HCI scan, WiFi scan trigger)
#   make deb              Debian / Raspberry Pi OS package in dist/ (host architecture)
#   make appimage         self-contained AppImage in dist/ (host architecture)
#   make docker-build     release .deb + AppImage built in a Debian container
#   make source-release   dist/rfguard-<ver>-src.tar.gz: the sources of this commit and of nilorea-library
#   make android          debug APK (see mk/android.mk)
#   make android-release  release-signed APK
#   make android-aab      release-signed App Bundle for Google Play
#   make store            Play Store screenshots, icon, feature graphic in store/ (see store/LISTING.md)
#   make show-version     print the version (show-version-code: the Android version code)
#   make bump-version     patch + 1 and version code + 1 (VERSION=x.y.z sets it; bump-version-code: code alone)
#                         No build changes the version: a release is bump, commit, build.
#   make clean / distclean
#
# Nilorea is compiled from source (not linked): NILOREA_DIR points at the checkout
# (git clone https://gitlab.com/gullradriel/nilorea-library.git).
#

# Searched, in order: ../nilorea-library (side by side with this project), then
# ../../nilorea-library. The first one holding include/nilorea/n_gui.h wins.
NILOREA_CANDIDATES = ../nilorea-library ../../nilorea-library
NILOREA_DIR ?= $(firstword $(foreach d,$(NILOREA_CANDIDATES),$(if $(wildcard $(d)/include/nilorea/n_gui.h),$(d))) ../../nilorea-library)
NIL := $(abspath $(NILOREA_DIR))

# Fail early with a useful message instead of a wall of missing-header errors
# (cleaning and showing the configuration work without the library).
NILOREA_FREE_GOALS = clean distclean show-config android-clean \
	show-version show-version-code bump-version bump-version-code
ifeq ($(wildcard $(NIL)/include/nilorea/n_gui.h),)
    ifneq ($(filter-out $(NILOREA_FREE_GOALS),$(or $(MAKECMDGOALS),all)),)
        $(error nilorea-library not found (looked in $(NILOREA_CANDIDATES)). Clone it next to this project: git clone https://gitlab.com/gullradriel/nilorea-library.git ../nilorea-library   or pass NILOREA_DIR=/path/to/nilorea-library)
    endif
endif

# android/version_name.txt is the single source of truth for the version;
# it changes only with `make bump-version` (version targets further down)
APP_VERSION := $(shell cat android/version_name.txt 2>/dev/null || echo 0.1.0)

CC ?= gcc
PKG_CONFIG ?= pkg-config
UNAME_S := $(shell uname -s)
UNAME_M := $(shell uname -m)

ifeq ($(DEBUG),1)
    OBJDIR = obj-asan
    BIN = rfguard-asan
    OPTFLAGS = -g -O0 -fno-omit-frame-pointer -fsanitize=address,undefined
    LDOPT = -fsanitize=address,undefined
else
    OBJDIR = obj
    BIN = rfguard
    OPTFLAGS = -O2 -g
    LDOPT =
endif

WARN = -W -Wall -Wextra -Wshadow -Wformat=2 -Wno-unused-parameter
DEFS = -D_GNU_SOURCE -DHAVE_ALLEGRO -DALLEGRO_UNSTABLE -DHAVE_CJSON -DRFG_VERSION=\"$(APP_VERSION)\"
INCLUDE = -Isrc -I$(NIL)/include -I$(NIL)/external/cJSON

# Raspberry Pi: same Linux build, flagged so the platform name and defaults can differ
ifneq ($(wildcard /proc/device-tree/model),)
    ifneq ($(shell grep -ci raspberry /proc/device-tree/model 2>/dev/null),0)
        DEFS += -DRFG_RASPBERRY_PI
    endif
endif

# Optional libcurl for HTTPS (OSM tiles, Overpass); without it the curl tool is spawned
ifneq ($(FORCE_NO_CURL),1)
    ifeq ($(shell $(PKG_CONFIG) --exists libcurl && echo yes),yes)
        DEFS += -DHAVE_CURL
        CURL_CFLAGS := $(shell $(PKG_CONFIG) --cflags libcurl)
        CURL_LIBS := $(shell $(PKG_CONFIG) --libs libcurl)
    endif
endif

ALLEGRO_PKGS = allegro-5 allegro_main-5 allegro_font-5 allegro_ttf-5 allegro_primitives-5 allegro_image-5 allegro_audio-5 allegro_acodec-5 allegro_color-5 allegro_memfile-5 allegro_dialog-5
ALLEGRO_CFLAGS := $(shell $(PKG_CONFIG) --cflags $(ALLEGRO_PKGS) 2>/dev/null)
ALLEGRO_LIBS := $(shell $(PKG_CONFIG) --libs $(ALLEGRO_PKGS) 2>/dev/null)
ifeq ($(ALLEGRO_LIBS),)
    ALLEGRO_LIBS = -lallegro_dialog -lallegro_acodec -lallegro_audio -lallegro_color -lallegro_image -lallegro_main -lallegro_primitives -lallegro_ttf -lallegro_font -lallegro_memfile -lallegro
endif

CFLAGS += $(OPTFLAGS) -std=gnu17 $(WARN) $(DEFS) $(INCLUDE) $(ALLEGRO_CFLAGS) $(CURL_CFLAGS)
# --as-needed: only the libraries really used become DT_NEEDED, whatever the
# toolchain default, so the .deb Depends list below stays exact
LDLIBS = -Wl,--as-needed $(ALLEGRO_LIBS) $(CURL_LIBS) -lpthread -lm -lX11 -lz

# --------------------------------------------------------------------------
# Sources
# --------------------------------------------------------------------------

# Nilorea modules compiled into the app (n_gui needs n_wrap, n_gui_md, n_markdown,
# n_gui_popup and n_clipboard; cJSON backs layout persistence and our JSON files)
NIL_CORE = n_common n_log n_str n_list n_hash n_time
NIL_GUI = n_allegro5 n_clipboard n_wrap n_gui n_gui_md n_gui_popup n_markdown
NIL_CORE_SRC = $(addprefix $(NIL)/src/,$(addsuffix .c,$(NIL_CORE))) $(NIL)/external/cJSON/cJSON.c
NIL_GUI_SRC = $(addprefix $(NIL)/src/,$(addsuffix .c,$(NIL_GUI)))

# core = detection (pure C), app = registry/pipeline/storage (pure C, threads),
# platform = scanners/alerts/paths, gui = N_GUI views, main.c = event loop
CORE_SRC = $(sort $(wildcard src/core/*.c))
APP_SRC = $(sort $(wildcard src/app/*.c))
PLATFORM_SRC = $(sort $(wildcard src/platform/*.c))
GUI_SRC = $(sort $(wildcard src/gui/*.c))
MAIN_SRC = src/main.c

# every source with its object; objects are flat per tree so names must be unique
APP_ALL_SRC = $(CORE_SRC) $(APP_SRC) $(PLATFORM_SRC) $(GUI_SRC) $(MAIN_SRC)
APP_OBJ = $(patsubst src/%.c,$(OBJDIR)/%.o,$(APP_ALL_SRC))
NIL_CORE_OBJ = $(patsubst %.c,$(OBJDIR)/nil/%.o,$(notdir $(NIL_CORE_SRC)))
NIL_GUI_OBJ = $(patsubst %.c,$(OBJDIR)/nil/%.o,$(notdir $(NIL_GUI_SRC)))

# pure-C objects the unit tests link against (no Allegro, no platform)
TEST_LIB_OBJ = $(patsubst src/%.c,$(OBJDIR)/%.o,$(CORE_SRC) $(APP_SRC)) $(NIL_CORE_OBJ)

.PHONY: all clean distclean test tests check install uninstall setcap deb appimage docker-build run show-config

all: $(BIN)

$(BIN): $(APP_OBJ) $(NIL_CORE_OBJ) $(NIL_GUI_OBJ)
	$(CC) $(LDOPT) -o $@ $^ $(LDLIBS)

$(OBJDIR)/%.o: src/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -MMD -MP -c $< -o $@

$(OBJDIR)/nil/%.o: $(NIL)/src/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -Wno-shadow -Wno-format-nonliteral -MMD -MP -c $< -o $@

$(OBJDIR)/nil/cJSON.o: $(NIL)/external/cJSON/cJSON.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -MMD -MP -c $< -o $@

# --------------------------------------------------------------------------
# Unit tests: tests/test_<name>.c, one binary each, always ASan + UBSan
# --------------------------------------------------------------------------
TEST_SRC = $(sort $(wildcard tests/test_*.c))
# tests/support/*.c: stub platform (no radios, no network) + shared test helpers
TEST_SUPPORT = $(sort $(wildcard tests/support/*.c))
TEST_BIN = $(patsubst tests/%.c,tests/bin/%,$(TEST_SRC))

tests: $(TEST_BIN)

# depends on the library sources and headers too, or a stale binary would test old code
tests/bin/%: tests/%.c $(TEST_SUPPORT) $(CORE_SRC) $(APP_SRC) $(wildcard src/core/*.h src/app/*.h src/platform/rfg_platform.h tests/*.h tests/support/*.h)
	@$(MAKE) --no-print-directory DEBUG=1 test-lib
	@mkdir -p tests/bin
	$(CC) -g -O0 -fsanitize=address,undefined -std=gnu17 $(WARN) $(DEFS) $(INCLUDE) -Itests -o $@ $< $(TEST_SUPPORT) $(patsubst src/%.c,obj-asan/%.o,$(CORE_SRC) $(APP_SRC)) $(patsubst %.c,obj-asan/nil/%.o,$(notdir $(NIL_CORE_SRC))) -lpthread -lm $(CURL_LIBS)

.PHONY: test-lib
test-lib: $(TEST_LIB_OBJ)

test: $(TEST_BIN)
	@fail=0; for t in $(TEST_BIN); do \
		RFG_ASSETS=$(CURDIR)/assets ASAN_OPTIONS=detect_leaks=1 $$t >/dev/null 2>tests/bin/$$(basename $$t).log && echo "PASS $$(basename $$t)" || { echo "FAIL $$(basename $$t) (see tests/bin/$$(basename $$t).log)"; fail=1; }; \
	done; exit $$fail

# --------------------------------------------------------------------------
# Diagnostic CLI (tools/rfg_scan_cli.c): the Linux platform scanners without
# the GUI, prints every advert / fix / status. ./rfguard-scan-cli 20 --http https://example.com
# --------------------------------------------------------------------------
SCAN_CLI = rfguard-scan-cli$(if $(filter 1,$(DEBUG)),-asan,)
SCAN_CLI_OBJ = $(patsubst src/%.c,$(OBJDIR)/%.o,$(CORE_SRC) $(PLATFORM_SRC)) $(NIL_CORE_OBJ)

.PHONY: scan-cli
scan-cli: $(SCAN_CLI)

$(SCAN_CLI): tools/rfg_scan_cli.c $(SCAN_CLI_OBJ)
	$(CC) $(CFLAGS) $(LDOPT) -o $@ $^ $(LDLIBS)

check:
	cppcheck --enable=warning,performance,portability --inline-suppr --suppress=unmatchedSuppression --error-exitcode=1 -q -D__linux__ -Isrc src

# --------------------------------------------------------------------------
# Install / packaging (one staging macro shared by
# install, deb and appimage). Packages always ship the release binary
# ./rfguard (-O2 -g, no sanitizers): DEBUG=1 is refused for these goals.
#
#   make install [PREFIX=/usr/local] [DESTDIR=]   FHS install
#   make deb                                       dist/rfguard_<ver>_<arch>.deb
#   make appimage                                  dist/RFGuard-<ver>-<arch>.AppImage
#   make docker-build                              both, built in a Debian container
# --------------------------------------------------------------------------
PREFIX ?= /usr/local
DESTDIR ?=
DIST_DIR = dist
PKG_BIN = rfguard

ifeq ($(DEBUG),1)
    ifneq ($(filter install deb appimage,$(MAKECMDGOALS)),)
        $(error install / deb / appimage ship the release binary: run them without DEBUG=1)
    endif
endif

# Files installed by every Linux packaging path, relative to a prefix dir.
# Assets land in <prefix>/share/rfguard/assets, which the Linux platform
# layer probes relative to the binary (<exe dir>/../share/rfguard/assets).
define _rfg_stage
	install -d "$(1)/bin" "$(1)/share/rfguard/assets" "$(1)/share/applications" "$(1)/share/metainfo" "$(1)/share/icons/hicolor/512x512/apps" "$(1)/share/doc/rfguard/licenses"
	install -m 0755 $(PKG_BIN) "$(1)/bin/rfguard"
	cp -r assets/. "$(1)/share/rfguard/assets/"
	chmod -R u=rwX,go=rX "$(1)/share/rfguard/assets"
	install -m 0644 packaging/org.niloreastudio.rfguard.desktop "$(1)/share/applications/org.niloreastudio.rfguard.desktop"
	install -m 0644 packaging/org.niloreastudio.rfguard.appdata.xml "$(1)/share/metainfo/org.niloreastudio.rfguard.appdata.xml"
	install -m 0644 packaging/rfguard.png "$(1)/share/icons/hicolor/512x512/apps/rfguard.png"
	install -m 0644 LICENSE "$(1)/share/doc/rfguard/copyright"
	install -m 0644 README.md AUTHORS.md "$(1)/share/doc/rfguard/"
	install -m 0644 assets/licenses/* "$(1)/share/doc/rfguard/licenses/"
endef

install: $(PKG_BIN)
	@echo "Installing RFGuard $(APP_VERSION) into $(DESTDIR)$(PREFIX)..."
	$(call _rfg_stage,$(DESTDIR)$(PREFIX))
	@echo "Installed. Run: $(PREFIX)/bin/rfguard (BLE scan: sudo setcap cap_net_raw,cap_net_admin+eip $(PREFIX)/bin/rfguard)"

uninstall:
	rm -f "$(DESTDIR)$(PREFIX)/bin/rfguard"
	rm -f "$(DESTDIR)$(PREFIX)/share/applications/org.niloreastudio.rfguard.desktop" "$(DESTDIR)$(PREFIX)/share/applications/rfguard.desktop"
	rm -f "$(DESTDIR)$(PREFIX)/share/metainfo/org.niloreastudio.rfguard.appdata.xml"
	rm -f "$(DESTDIR)$(PREFIX)/share/icons/hicolor/512x512/apps/rfguard.png"
	rm -rf "$(DESTDIR)$(PREFIX)/share/rfguard" "$(DESTDIR)$(PREFIX)/share/doc/rfguard"

# BLE passive scanning opens a raw HCI socket and the WiFi scan trigger needs
# CAP_NET_ADMIN; granting the capabilities avoids running the GUI as root.
setcap: $(BIN)
	sudo setcap 'cap_net_raw,cap_net_admin+eip' $(BIN)

# --------------------------------------------------------------------------
# deb: Debian / Ubuntu / Raspberry Pi OS package via dpkg-deb (no root needed).
# The architecture is the build host's (amd64, arm64, armhf on a Pi): build
# natively, or in docker-build with --platform for another architecture.
# --------------------------------------------------------------------------
DEB_ARCH ?= $(shell dpkg --print-architecture 2>/dev/null || echo amd64)
DEB_ROOT = $(DIST_DIR)/deb/rfguard_$(APP_VERSION)_$(DEB_ARCH)
DEB_FILE = $(DIST_DIR)/rfguard_$(APP_VERSION)_$(DEB_ARCH).deb

# One alternative pair per package the binary actually links (the link uses
# --as-needed, check with `readelf -d rfguard | grep NEEDED`): the t64 name
# since the 64-bit time_t transition (Debian trixie, Ubuntu noble, Raspberry Pi
# OS trixie) first, the older name for bookworm / jammy. Debian has no separate
# primitives / font / color / memfile packages: those addons live in the base
# liballegro5.2* package (`dpkg -S liballegro_primitives`). acodec and dialog
# are not linked (tones are synthesized, no native dialog is used), so they are
# not depended on (dialog would pull in GTK). libcap2-bin provides setcap for
# the postinst.
DEB_DEPENDS = liballegro5.2t64 | liballegro5.2, \
liballegro-image5.2t64 | liballegro-image5.2, \
liballegro-ttf5.2t64 | liballegro-ttf5.2, \
liballegro-audio5.2t64 | liballegro-audio5.2, \
libcurl4t64 | libcurl4, libx11-6, libcap2-bin
DEB_RECOMMENDS = gpsd, espeak-ng

deb: $(PKG_BIN)
	@command -v dpkg-deb >/dev/null || { echo "ERROR: dpkg-deb not found (install dpkg)"; exit 1; }
	@echo "Building $(DEB_FILE)..."
	@rm -rf "$(DEB_ROOT)"
	$(call _rfg_stage,$(DEB_ROOT)/usr)
	@install -d "$(DEB_ROOT)/DEBIAN"
	@printf 'Package: rfguard\nVersion: %s\nSection: net\nPriority: optional\nArchitecture: %s\nDepends: %s\nRecommends: %s\nInstalled-Size: %s\nMaintainer: GullRaDriel <gullradriel@gmail.com>\nHomepage: https://gitlab.com/gullradriel/rfguard\nDescription: Passive BLE and WiFi surveillance-equipment detector\n Listens to Bluetooth LE advertisements and WiFi beacons and flags body\n cameras, plate readers, drones, trackers and other surveillance gear.\n Receive-only. C / Allegro 5 rebuild based on Wardrive Go by RocketGod,\n the original work (GPL-3.0).\n' \
		"$(APP_VERSION)" "$(DEB_ARCH)" "$(DEB_DEPENDS)" "$(DEB_RECOMMENDS)" "$$(du -sk "$(DEB_ROOT)/usr" | cut -f1)" > "$(DEB_ROOT)/DEBIAN/control"
	@install -m 0755 packaging/postinst "$(DEB_ROOT)/DEBIAN/postinst"
	@dpkg-deb --build --root-owner-group "$(DEB_ROOT)" "$(DEB_FILE)"
	@echo "Built $(DEB_FILE)"

# --------------------------------------------------------------------------
# appimage: the binary + every non-glibc .so it needs, in one file.
# The architecture follows the build host: dpkg's userland architecture when
# known (a Pi with a 64-bit kernel and a 32-bit userland reports uname -m
# aarch64 but needs the armhf tool), uname -m otherwise. appimagetool for that
# architecture is fetched on first use into dist/ (override APPIMAGETOOL for a
# local copy); --appimage-extract-and-run avoids needing FUSE in containers.
# File capabilities do not survive inside an AppImage: see docs/LINUX.md.
# --------------------------------------------------------------------------
APPIMAGE_ARCH := $(or $(patsubst amd64,x86_64,$(patsubst arm64,aarch64,$(patsubst i386,i686,$(filter amd64 arm64 armhf i386,$(DEB_ARCH))))),$(patsubst armv%,armhf,$(patsubst arm64,aarch64,$(UNAME_M))))
MULTIARCH := $(shell $(CC) -print-multiarch 2>/dev/null)
APPDIR = $(DIST_DIR)/RFGuard.AppDir
APPIMAGE_FILE = $(DIST_DIR)/RFGuard-$(APP_VERSION)-$(APPIMAGE_ARCH).AppImage
APPIMAGETOOL ?= $(DIST_DIR)/appimagetool-$(APPIMAGE_ARCH).AppImage
# extra appimagetool options, e.g. APPIMAGETOOL_FLAGS=-n skips the AppStream
# check (it fetches the homepage URL, which fails while the repo is offline)
APPIMAGETOOL_FLAGS ?=
APPIMAGETOOL_URL = https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$(APPIMAGE_ARCH).AppImage

# Libraries Allegro's GLX display driver and libepoxy / GLVND dlopen() while
# creating the OpenGL context: opened by name, so ldd never lists them, and the
# AppImage dies with "cannot open shared object file" on a host without the
# full X11 / XCB client stack. Generic X-protocol client shims, safe to ship.
# Deliberately NOT bundled (machine-specific, must come from the host): the
# GPU driver proper (libGLX_*, dri / swrast modules, libnvidia-*, libdrm).
APPIMAGE_EXTRA_SONAMES = \
	libX11-xcb.so.1 \
	libxcb-glx.so.0 \
	libxcb-dri2.so.0 \
	libxcb-dri3.so.0 \
	libxcb-present.so.0 \
	libxcb-sync.so.1 \
	libxcb-randr.so.0 \
	libxcb-xfixes.so.0 \
	libxshmfence.so.1

# Libraries ldd lists that must come from the host (a shell case pattern):
# glibc and its loader (version-locked together), the GLVND / GL dispatch and
# libdrm (tied to the host GPU driver), and libstdc++ / libgcc_s (the host's
# Mesa or NVIDIA driver is loaded into the process and may need a newer
# libstdc++ than the build host's; every desktop has one).
APPIMAGE_HOST_LIBS = libc.so.*|libm.so.*|libmvec.so.*|libpthread.so.*|libdl.so.*|librt.so.*|libresolv.so.*|libutil.so.*|libanl.so.*|libnsl.so.*|libnss_*|ld-linux*|libGL.so.*|libGLX.so.*|libGLdispatch.so.*|libOpenGL.so.*|libEGL.so.*|libdrm.so.*|libstdc++.so.*|libgcc_s.so.*

$(APPIMAGETOOL):
	@mkdir -p "$(dir $(APPIMAGETOOL))"
	@echo "Fetching appimagetool ($(APPIMAGE_ARCH))..."
	@curl -fL "$(APPIMAGETOOL_URL)" -o "$(APPIMAGETOOL).part"
	@chmod +x "$(APPIMAGETOOL).part" && mv "$(APPIMAGETOOL).part" "$(APPIMAGETOOL)"

appimage: $(PKG_BIN) $(APPIMAGETOOL)
	@echo "Building $(APPIMAGE_FILE)..."
	@rm -rf "$(APPDIR)"
	$(call _rfg_stage,$(APPDIR)/usr)
	@install -d "$(APPDIR)/usr/lib"
	@# every shared lib the binary needs except APPIMAGE_HOST_LIBS
	@for lib in $$(ldd $(PKG_BIN) | awk '{print $$3}' | grep -E '^/'); do \
		base=$$(basename "$$lib"); \
		case "$$base" in \
			$(APPIMAGE_HOST_LIBS)) ;; \
			*) cp -L "$$lib" "$(APPDIR)/usr/lib/" ;; \
		esac; \
	done
	@# the dlopen()-ed X11 / XCB libs ldd cannot see, through the linker cache
	@# with a multiarch directory fallback; a missing one is only warned about
	@for soname in $(APPIMAGE_EXTRA_SONAMES); do \
		[ -e "$(APPDIR)/usr/lib/$$soname" ] && continue; \
		path=$$(PATH="/sbin:/usr/sbin:$$PATH" ldconfig -p 2>/dev/null | awk -v s="$$soname" '$$1==s {print $$NF; exit}'); \
		if [ -z "$$path" ]; then \
			for d in /usr/lib/$(MULTIARCH) /lib/$(MULTIARCH) /usr/lib64 /usr/lib; do \
				[ -e "$$d/$$soname" ] && { path="$$d/$$soname"; break; }; \
			done; \
		fi; \
		if [ -n "$$path" ] && [ -e "$$path" ]; then \
			cp -L "$$path" "$(APPDIR)/usr/lib/$$soname"; \
		else \
			echo "  warning: $$soname not found on build host, not bundled"; \
		fi; \
	done
	@install -m 0755 packaging/AppRun "$(APPDIR)/AppRun"
	@install -m 0644 packaging/org.niloreastudio.rfguard.desktop "$(APPDIR)/org.niloreastudio.rfguard.desktop"
	@install -m 0644 packaging/rfguard.png "$(APPDIR)/rfguard.png"
	@install -m 0644 packaging/rfguard.png "$(APPDIR)/.DirIcon"
	@ARCH=$(APPIMAGE_ARCH) "$(APPIMAGETOOL)" --appimage-extract-and-run $(APPIMAGETOOL_FLAGS) "$(APPDIR)" "$(APPIMAGE_FILE)"
	@echo "Built $(APPIMAGE_FILE)"

# --------------------------------------------------------------------------
# docker-build: release .deb + AppImage built in a Debian container
# (packaging/Dockerfile, default debian:trixie-slim, BASE_IMAGE overridable,
# PLATFORM=linux/arm64 for another architecture through binfmt / qemu). The
# sibling nilorea-library (NILOREA_DIR) is mounted next to the repo. The
# artifacts carry the Debian codename: dist/rfguard_<ver>-<codename>_<arch>.deb
# --------------------------------------------------------------------------
docker-build:
	NILOREA_DIR="$(NIL)" APPIMAGETOOL_FLAGS="$(APPIMAGETOOL_FLAGS)" sh packaging/docker-build.sh

# --------------------------------------------------------------------------
# source-release: the complete source of a release, RFGuard and
# nilorea-library at the commits built, in one tarball that builds on its own
# with `make NILOREA_DIR=nilorea-library`. A GPL binary comes with, or points
# at, all of its source, and nilorea is compiled into it: this file goes
# wherever the packages go. Only committed work goes in: a tree with
# uncommitted changes is refused, so the tarball is exactly the commits that
# SOURCE-RELEASE.txt names.
# --------------------------------------------------------------------------
SRC_STAGE   = $(DIST_DIR)/src-release/rfguard-$(APP_VERSION)
SRC_RELEASE = $(DIST_DIR)/rfguard-$(APP_VERSION)-src.tar.gz
# Working notes of the repositories, not source: left out of the tarball.
SRC_EXCLUDE = --exclude=CLAUDE.md --exclude=CLAUDE.local.md --exclude=.claude
.PHONY: source-release
source-release:
	@git diff --quiet HEAD -- && git -C "$(NIL)" diff --quiet HEAD -- || { \
		echo "ERROR: commit RFGuard and nilorea-library first: the source release is"; \
		echo "       made of commits, so that it is exactly what a build was made from."; exit 1; }
	rm -rf "$(DIST_DIR)/src-release"
	install -d "$(SRC_STAGE)/nilorea-library"
	git archive --format=tar HEAD | tar -x $(SRC_EXCLUDE) -C "$(SRC_STAGE)"
	git -C "$(NIL)" archive --format=tar HEAD | tar -x $(SRC_EXCLUDE) -C "$(SRC_STAGE)/nilorea-library"
	printf 'RFGuard %s, commit %s\nnilorea-library, commit %s\n\nBuild with: make NILOREA_DIR=nilorea-library\n' \
	    "$(APP_VERSION)" "`git rev-parse HEAD`" "`git -C "$(NIL)" rev-parse HEAD`" > "$(SRC_STAGE)/SOURCE-RELEASE.txt"
	tar -C "$(DIST_DIR)/src-release" -czf "$(SRC_RELEASE)" "rfguard-$(APP_VERSION)"
	@echo "Built $(SRC_RELEASE)"

# the AppImage architecture name (used by packaging/docker-build.sh)
.PHONY: print-appimage-arch
print-appimage-arch:
	@echo $(APPIMAGE_ARCH)

run: $(BIN)
	./$(BIN)

# --------------------------------------------------------------------------
# Google Play store assets (store/LISTING.md)
#   store-shots  the app in demo mode on a virtual phone screen (Xvfb), touch
#                layout, throw-away data dir: --shots tours the views and saves
#                one raw capture per view into store/raw/
#   store-art    captioned screenshots, icon and feature graphic from store/raw/
#                (tools/gen_store.py, Pillow), then the listing text limits
# --------------------------------------------------------------------------
STORE_DIR = store
STORE_WORK = build_store
STORE_W ?= 1080
STORE_H ?= 1920
STORE_DENSITY ?= 2.75

.PHONY: store store-shots store-art
store: store-shots store-art

store-shots: $(BIN)
	@command -v xvfb-run >/dev/null 2>&1 || { echo "ERROR: xvfb-run not found (apt install xvfb)"; exit 1; }
	@rm -rf $(STORE_WORK) $(STORE_DIR)/raw
	@mkdir -p $(STORE_WORK)/data $(STORE_DIR)/raw
	XDG_DATA_HOME=$(abspath $(STORE_WORK)/data) RFG_TOUCH=1 RFG_DENSITY=$(STORE_DENSITY) \
		xvfb-run -a -s "-screen 0 $(STORE_W)x$(STORE_H)x24" \
		./$(BIN) --shots $(STORE_DIR)/raw --width $(STORE_W) --height $(STORE_H)
	@ls $(STORE_DIR)/raw/*.png >/dev/null 2>&1 || { echo "ERROR: no capture written to $(STORE_DIR)/raw"; exit 1; }

store-art:
	@python3 -c "import PIL" 2>/dev/null || { echo "ERROR: Pillow not found (apt install python3-pil)"; exit 1; }
	python3 tools/gen_store.py
	python3 tools/check_listing.py

show-config:
	@echo "version  : $(APP_VERSION)"
	@echo "platform : $(UNAME_S) $(UNAME_M)"
	@echo "defines  : $(DEFS)"
	@echo "nilorea  : $(NIL)"
	@echo "allegro  : $(ALLEGRO_LIBS)"
	@echo "curl     : $(if $(CURL_LIBS),libcurl,curl tool fallback)"

# ---------------------------------------------------------------------------
# version: android/version_name.txt (x.y.z) and android/version_code.txt
# (Android version code) change only through the targets below, never as a
# side effect of a build. A release is: make bump-version, commit, build.
#   make show-version                 print the version
#   make show-version-code            print the Android version code
#   make bump-version                 patch + 1 (x.y.z to x.y.z+1) and code + 1
#   make bump-version VERSION=x.y.z   set that version, code + 1
#   make bump-version-code            code + 1 alone (same version sent to
#                                     Google Play again: it refuses a known code)
# ---------------------------------------------------------------------------
VERSION_NAME_FILE = android/version_name.txt
VERSION_CODE_FILE = android/version_code.txt
VERSION_RE = ^[0-9]+\.[0-9]+\.[0-9]+$$
VERSION_NEXT_CODE = CODE=$$(cat $(VERSION_CODE_FILE)); \
	printf '%s\n' "$$CODE" | grep -Eqx '[0-9]+' || { echo "ERROR: $(VERSION_CODE_FILE) holds '$$CODE', not a number" >&2; exit 1; }; \
	NCODE=$$(expr "$$CODE" + 1)

.PHONY: show-version show-version-code bump-version bump-version-code
show-version:
	@cat $(VERSION_NAME_FILE)

show-version-code:
	@cat $(VERSION_CODE_FILE)

bump-version:
	@set -e; OLD=$$(cat $(VERSION_NAME_FILE)); NEW='$(if $(filter command line,$(origin VERSION)),$(VERSION))'; \
	if [ -z "$$NEW" ]; then \
		printf '%s\n' "$$OLD" | grep -Eqx '$(VERSION_RE)' || { echo "ERROR: $(VERSION_NAME_FILE) holds '$$OLD', not x.y.z: pass VERSION=x.y.z" >&2; exit 1; }; \
		NEW="$${OLD%.*}.$$(expr "$${OLD##*.}" + 1)"; \
	fi; \
	printf '%s\n' "$$NEW" | grep -Eqx '$(VERSION_RE)' || { echo "ERROR: VERSION must be x.y.z (digits only), got '$$NEW'" >&2; exit 1; }; \
	$(VERSION_NEXT_CODE); \
	echo "$$NEW" > $(VERSION_NAME_FILE); echo "$$NCODE" > $(VERSION_CODE_FILE); \
	echo "$$OLD -> $$NEW (code $$CODE -> $$NCODE)"

bump-version-code:
	@set -e; $(VERSION_NEXT_CODE); \
	echo "$$NCODE" > $(VERSION_CODE_FILE); echo "$$CODE -> $$NCODE"

clean:
	rm -rf obj obj-asan tests/bin build_store rfguard rfguard-asan rfguard-scan-cli rfguard-scan-cli-asan

distclean: clean
	rm -rf dist

# Android targets (NDK + Allegro monolith, APK assembled by hand, no Gradle)
-include mk/android.mk

-include $(APP_OBJ:.o=.d) $(NIL_CORE_OBJ:.o=.d) $(NIL_GUI_OBJ:.o=.d)
