# SPDX-License-Identifier: GPL-3.0-or-later
# AfterAPro - non-destructive RAW photo editor
#
# Build approach inherited from Sketchr and Fissure and recorded in
# docs/dev/DECISIONS.md D1: nilorea-library is NOT linked. The modules the
# program uses are compiled from source out of NILOREA_DIR, so a sanitizer
# build instruments them too and there is no ABI to keep in step.
#
# Usage:
#   make                    host binary, release flags
#   make debug              host binary with ASan and UBSan
#   make test               unit tests and the headless smoke test
#   make docs               api + html + pdf
#   make check-format       clang-format and clang-tidy
#   make windows            mingw64 cross build
#   make deb                .deb for the host distribution, in dist/
#   make appimage           self-contained AppImage, in dist/
#   make docker-build       both, built in a Debian trixie container
#   make show-version       print the version
#   make bump-version       minor + 1; VERSION=x.y.z sets it. Nothing else
#                           changes the version: bump, commit, build.
#   make clean / distclean

# The first target in a makefile is the one a bare `make` builds. Saying so
# rather than relying on the order: adding a rule above this line once made
# `make` build the plugins and nothing else, silently, for half an hour.
.DEFAULT_GOAL := all

# The version, read from APRO_VERSION in include/apro_version.h, the one
# place it is stored (tools/apro-version.sh). No target writes it but
# bump-version below; the -MMD dependencies rebuild what includes the header
# when it moves.
APRO_VERSION_STR := $(shell sh tools/apro-version.sh)

# show-version prints the stored version and nothing else. bump-version is
# the only target that changes it: minor + 1, or VERSION=x.y.z for an exact
# value, refused when it is not three numbers. A release is: bump, commit,
# build. A build made twice gives the same file names.
show-version:
	@sh tools/apro-version.sh

bump-version:
	@sh tools/apro-version.sh $(if $(filter command line,$(origin VERSION)),--set '$(VERSION)',--bump)

CC             = gcc
CXX            = g++
PKG_CONFIG    ?= pkg-config
WINDOWS_CC     = x86_64-w64-mingw32-gcc
WINDOWS_CXX    = x86_64-w64-mingw32-g++
WINDOWS_PKG_CONFIG = x86_64-w64-mingw32-pkg-config
NILOREA_DIR   ?= ../../nilorea-library
BINARY         = afterapro
OBJDIR         = obj
LIBRAW_DIR     = external/LibRaw
DOXYGEN        = doxygen
PANDOC         = pandoc

SQLITE_PKG   = sqlite3
IMAGE_PKGS   = libjpeg libpng

# The Windows cross build from Linux, which `make windows` runs as
# `make WINCROSS=1 all`. There is no mingw pkg-config on a Linux distribution
# and no mingw Allegro, so the libraries come from external/mingw, which
# `make windows-deps` fills: Allegro's own mingw release and its dependency
# pack for Allegro, zlib, libjpeg and libpng, SQLite's amalgamation compiled
# in, and Little CMS from its source for soft proofing (D185). The compiler is
# the posix threads mingw, because the Allegro release was built with one and
# its DLLs import that runtime's libstdc++ and libgcc. lensfun and libxml2
# have no mingw build here and stay off, as on a Linux machine without them.
MINGW_DEPS_DIR = external/mingw
MINGW_SQLITE   = $(MINGW_DEPS_DIR)/sqlite-amalgamation-3530400
MINGW_LCMS2    = $(MINGW_DEPS_DIR)/lcms2-2.17
WINCROSS_CC   ?= x86_64-w64-mingw32-gcc-posix
WINCROSS_CXX  ?= x86_64-w64-mingw32-g++-posix
ifeq ($(WINCROSS),1)
  CC       = $(WINCROSS_CC)
  CXX      = $(WINCROSS_CXX)
  AR       = x86_64-w64-mingw32-ar
  OS       = Windows_NT
  OBJDIR   = obj-win
  LENSFUN  = 0
  LIBXML2  = 0
  LCMS2    = 0
  DEP_CFLAGS  = -I$(MINGW_DEPS_DIR)/allegro/include -I$(MINGW_DEPS_DIR)/allegro_deps/include \
                -I$(MINGW_SQLITE) -DAPRO_HAVE_LCMS2 -I$(MINGW_LCMS2)/include
  # Allegro links against its import libraries and its DLLs travel with the
  # program. zlib, libjpeg and libpng are static archives in the pack, but
  # allegro_image and allegro_ttf, which hold them, export their symbols, and
  # the linker meets those import libraries first: afterapro.exe calls the
  # copies inside the two DLLs and carries none of its own (D383). libstdc++,
  # libgcc and winpthread stay DLLs: Allegro's own DLLs import them, so they
  # ship whatever this does, and one copy of each runtime in the process is
  # one copy of its state.
  DEP_LIBS    = -L$(MINGW_DEPS_DIR)/allegro/lib -L$(MINGW_DEPS_DIR)/allegro_deps/lib \
                $(addprefix -l,$(subst -5,,$(ALLEGRO_PKGS))) -lpng16 -ljpeg
  ZLIB_LIB    = -lzlib
  WINDRES     = x86_64-w64-mingw32-windres
  EXTRA_OBJ   = $(OBJDIR)/sqlite3.o $(OBJDIR)/lcms2.a
endif

# lensfun is optional. With it, a lens is matched from the EXIF and corrected
# from the calibrations the database ships; without it, the same corrections
# come from the profiles saved in the settings directory and from the sliders.
# Detected rather than required, so a machine without the development package
# still builds: LENSFUN=0 forces it off.
LENSFUN ?= auto
ifeq ($(LENSFUN),auto)
  HAVE_LENSFUN := $(shell $(PKG_CONFIG) --exists lensfun && echo 1)
else ifeq ($(LENSFUN),0)
  HAVE_LENSFUN :=
else
  HAVE_LENSFUN := 1
endif
ifeq ($(HAVE_LENSFUN),1)
  LENSFUN_CFLAGS = -DAPRO_HAVE_LENSFUN $(shell $(PKG_CONFIG) --cflags lensfun)
  LENSFUN_LIBS   = $(shell $(PKG_CONFIG) --libs lensfun)
else
  LENSFUN_CFLAGS =
  LENSFUN_LIBS   =
endif
# libxml2 is optional too. With it, an XMP file is kept beside each photograph
# for darktable, Lightroom and exiftool to read, merged into when one is
# already there (DECISIONS.md D129); without it the setting says it is not
# built in. LIBXML2=0 forces it off.
LIBXML2 ?= auto
ifeq ($(LIBXML2),auto)
  HAVE_LIBXML2 := $(shell $(PKG_CONFIG) --exists libxml-2.0 && echo 1)
else ifeq ($(LIBXML2),0)
  HAVE_LIBXML2 :=
else
  HAVE_LIBXML2 := 1
endif
ifeq ($(HAVE_LIBXML2),1)
  LIBXML2_CFLAGS = -DAPRO_HAVE_LIBXML2 $(shell $(PKG_CONFIG) --cflags libxml-2.0)
  LIBXML2_LIBS   = $(shell $(PKG_CONFIG) --libs libxml-2.0)
else
  LIBXML2_CFLAGS =
  LIBXML2_LIBS   =
endif
# lcms2 is optional as well. With it, the loupe can show a photograph as a
# printer or another screen would reproduce it (soft proofing, D163); without
# it the setting says it is not built in. LCMS2=0 forces it off.
LCMS2 ?= auto
ifeq ($(LCMS2),auto)
  HAVE_LCMS2 := $(shell $(PKG_CONFIG) --exists lcms2 && echo 1)
else ifeq ($(LCMS2),0)
  HAVE_LCMS2 :=
else
  HAVE_LCMS2 := 1
endif
ifeq ($(HAVE_LCMS2),1)
  LCMS2_CFLAGS = -DAPRO_HAVE_LCMS2 $(shell $(PKG_CONFIG) --cflags lcms2)
  # Debian's lcms2.pc names its two plugins as well. Neither is used: the
  # proof converts through its own colour table (D183), so linking them
  # only put two libraries on the link line; a linker without --as-needed
  # (Debian's has it) made the program load them at every start.
  LCMS2_LIBS   = $(filter-out -llcms2_threaded -llcms2_fast_float,$(shell $(PKG_CONFIG) --libs lcms2))
else
  LCMS2_CFLAGS =
  LCMS2_LIBS   =
endif
# No audio addon: the program makes no sound, and allegro_audio and
# allegro_acodec were linked and never called (D258).
ALLEGRO_PKGS = allegro-5 allegro_font-5 allegro_ttf-5 allegro_primitives-5 \
               allegro_image-5 allegro_dialog-5 allegro_color-5 \
               allegro_memfile-5
# What the libraries above need to compile and link. pkg-config answers on
# Linux and on MSYS2; the cross build sets them itself, above.
DEP_CFLAGS ?= $(shell $(PKG_CONFIG) --cflags $(ALLEGRO_PKGS) $(SQLITE_PKG) $(IMAGE_PKGS))
DEP_LIBS   ?= $(shell $(PKG_CONFIG) --libs $(ALLEGRO_PKGS) $(SQLITE_PKG) $(IMAGE_PKGS))
ZLIB_LIB   ?= -lz

# Sanitizers: `make debug` is the documented entry point, SAN= is for a
# targeted run.
#
# An instrumented build uses its own object directory. Sharing one with the
# release build means a plain `make` afterwards sees the instrumented objects
# as up to date and relinks them into what looks like a release binary; that
# cost an afternoon once, when the smoke test failed because the binary it ran
# was quietly still an ASan one.
#
# The binary and the test binaries are per build too: afterapro-asan and
# obj-asan/tests/, and so on. A release `make test` used to find test binaries
# an instrumented build had left, newer than its objects, and run those.
#
# CLANG=1 builds with clang and clang++ instead, into obj-clang, as a second
# compiler's opinion on the same -Werror code. It combines with SAN and DEBUG:
# CLANG=1 SAN=asan is obj-clang-asan.
MODE =
ifeq ($(SAN),asan)
  SANITIZE = -fsanitize=address,undefined -fno-omit-frame-pointer -g -O1
  MODE = -asan
else ifeq ($(SAN),tsan)
  SANITIZE = -fsanitize=thread -fno-omit-frame-pointer -g -O1
  MODE = -tsan
else ifeq ($(DEBUG),1)
  SANITIZE = -fsanitize=address,undefined -g -O0
  MODE = -debug
else
  SANITIZE = -O3
endif
ifeq ($(CLANG),1)
  CC = clang
  CXX = clang++
  MODE := -clang$(MODE)
endif
ifneq ($(MODE),)
  OBJDIR = obj$(MODE)
endif
# What `all` links and `test` runs. Packaging and the Windows build use the
# release $(BINARY) itself.
BUILD_BIN = $(BINARY)$(MODE)
# Where the test binaries go: tests/ for the release build, as always, and the
# build's own object directory for any other.
TEST_OUT = $(if $(MODE),$(OBJDIR)/tests,tests)

WARN     = -Wall -Wextra -Wformat=2 -Wshadow
# -Werror applies to AfterAPro's own translation units only. nilorea and cJSON
# are third-party here: their warnings are theirs to fix upstream, and failing
# our build on them would only tempt us to patch a tree we do not own.
OWN_WARN = -Werror

# gnu17 rather than c11: nilorea's sources are compiled into this binary and
# need it. AfterAPro's own code stays C11. See docs/dev/DECISIONS.md D2.
# ENABLE_LOCALES is not cJSON asking to be localised: without it cJSON assumes
# the C library writes a '.' and looks for that when normalising a number, so
# on a machine whose locale writes a comma it emits "0,5" and produces JSON
# that nothing else can read. With it, it asks localeconv and replaces
# properly. In CFLAGS rather than on the cJSON object rule, because the test
# binaries compile cJSON themselves and would otherwise disagree with the
# program about what a number looks like.
CFLAGS   = $(WARN) $(SANITIZE) -std=gnu17 -D_GNU_SOURCE -DHAVE_ALLEGRO -DHAVE_CJSON \
           -DENABLE_LOCALES \
           -DALLEGRO_UNSTABLE \
           -Iinclude -I$(abspath $(NILOREA_DIR))/include \
           -I$(abspath $(NILOREA_DIR))/external/cJSON \
           -I$(LIBRAW_DIR) -Iexternal/onnxruntime \
           $(DEP_CFLAGS) \
           $(LENSFUN_CFLAGS) $(LIBXML2_CFLAGS) $(LCMS2_CFLAGS) $(PLATFORM_CFLAGS)
LDFLAGS  = $(SANITIZE)
# -lstdc++ and -lz are LibRaw's: it is C++ internally and uses zlib for the
# floating point DNG path. AfterAPro's own sources stay C and touch only its
# C API (DECISIONS.md D12).
LDLIBS   = $(DEP_LIBS) \
           $(LENSFUN_LIBS) $(LIBXML2_LIBS) $(LCMS2_LIBS) -lpthread -lm -lstdc++ $(ZLIB_LIB)

ifeq ($(OS),Windows_NT)
  EXE = .exe
  PLUGIN_EXT = .dll
  # Without -mwindows the loader opens a console behind the GUI on every run.
  WIN_SUBSYSTEM = -mwindows
  # -lshell32 backs apro_platform_trash(), which is SHFileOperationW. mingw
  # links it by default today and naming it is what keeps that from being a
  # thing to find out about later.
  # -lgdi32 backs apro_platform_display_icc(), which is GetICMProfileW.
  # -lbcrypt backs nilorea's n_hash.c, whose tables take a random seed
  # from BCryptGenRandom (nilorea a42ff76).
  PLATFORM_LIBS = -lws2_32 -lshell32 -lgdi32 -lbcrypt
  # Everything is position independent on Windows and the flag is a warning
  # there, which -Werror would turn into a failed build.
  PLUGIN_PIC =
  # A DLL exports every symbol when none is marked, which is what the plugins
  # rely on rather than sprinkling __declspec through a header that has to
  # compile on both systems.
  #
  # __USE_MINGW_ANSI_STDIO makes printf the C99 one rather than the one the
  # old Microsoft runtime shipped. Without it %zu prints the letters z and u,
  # which turns every size in every log line into nonsense, and nilorea's
  # logging is full of them.
  PLATFORM_CFLAGS = -D__USE_MINGW_ANSI_STDIO=1
  # The icon, compiled into the exe (packaging/windows/afterapro.rc).
  WINDRES ?= windres
  EXTRA_OBJ += $(OBJDIR)/afterapro_res.o
  # Each plugin DLL links a version resource of its own (version.rc).
  PLUGIN_RES = $(OBJDIR)/plugin_res/%.o
else
  EXE =
  PLUGIN_EXT = .so
  WIN_SUBSYSTEM =
  # -lX11 backs nilorea n_clipboard's X11 selection owner, which n_gui pulls in,
  # and apro_platform_modifiers(), which asks the server which keys are held.
  # -ldl backs nilorea n_module's dlopen: in libc from glibc 2.34, a library
  # of its own before that.
  PLATFORM_LIBS = -lX11 -ldl
  PLUGIN_PIC = -fPIC
  PLATFORM_CFLAGS =
endif

# nilorea modules compiled into the binary. n_wrap is not optional: n_gui calls
# its word wrap. n_clipboard is not optional either: n_gui includes it. Nor are
# n_markdown and n_gui_md: n_gui's markdown view is built on them, so a build
# without them does not link whether or not this program shows any markdown.
# n_module opens the OpenCL loader, ONNX Runtime and the plugins; n_sha256
# checks a downloaded model; n_disk_cache holds the
# thumbnails; n_mem_cache the stamps the plugin host draws for a watermark,
# n_font_file the bold and italic faces of the font it draws them in;
# n_tiff reads DCP camera profiles; n_icc finds the colour profile
# a JPEG, PNG, TIFF or WebP carries; n_linalg solves the least squares fits of
# the sky gradient and the wide-field star registration.
NILOREA_MODULES = n_common n_log n_str n_list n_hash n_time n_wrap n_clipboard \
                  n_markdown n_gui_md \
                  n_thread_pool n_files n_gui n_gui_color n_gui_curve n_gui_colorwheel n_gui_grid n_gui_popup n_module n_disk_cache n_mem_cache n_font_file \
                  n_tiff n_icc n_sha256 n_zip n_pth n_linalg
NIL_SRC  = $(addprefix $(NILOREA_DIR)/src/,$(addsuffix .c,$(NILOREA_MODULES)))
CJSON_SRC = $(NILOREA_DIR)/external/cJSON/cJSON.c

# LibRaw is vendored under external/LibRaw (external/VENDOR.md records the
# revision). It is third-party C++: built with warnings relaxed, the same way
# Fissure builds its vendored QuickJS, because its warnings are upstream's to
# fix and 83 files of noise would bury ours.
# The three *_ph.cpp files are placeholders: LibRaw ships them so a reduced
# build can leave a subsystem out, and they define the same symbols as the real
# implementations. Compiling both is a duplicate definition at link time.
LIBRAW_ALL_SRC = $(wildcard $(LIBRAW_DIR)/src/*.cpp) $(wildcard $(LIBRAW_DIR)/src/*/*.cpp)
LIBRAW_SRC = $(filter-out %_ph.cpp,$(LIBRAW_ALL_SRC))
LIBRAW_OBJ = $(patsubst $(LIBRAW_DIR)/src/%.cpp,$(OBJDIR)/libraw/%.o,$(LIBRAW_SRC))
# USE_JPEG and USE_X3FTOOLS are not defaults and both cost formats when they
# are left out. Without USE_JPEG, LibRaw's internal/defines.h defines NO_JPEG,
# and identify.cpp then sets is_raw = 0 for a lossy compressed DNG and for a
# Kodak JPEG raw: the file is refused at open rather than decoded. Without
# USE_X3FTOOLS every line of src/x3f compiles to nothing and parse_x3f() does
# nothing, so a Sigma Foveon file cannot be read at all. The jpeg one is free:
# this program already links libjpeg for its own export writer, which is where
# the flags below come from.
# LIBRAW_NOTHREADS is not set, on purpose: it turns the bit reader's state
# into statics shared by every LibRaw object in the process, and thumbnail
# workers decode several files at once. Two CR2 decodes in parallel then read
# each other's bits and came out black or garbled (DECISIONS.md D147).
LIBRAW_CXXFLAGS = -O3 -w -DUSE_ZLIB -DUSE_JPEG -DUSE_X3FTOOLS \
                  $(if $(filter 1,$(WINCROSS)),-I$(MINGW_DEPS_DIR)/allegro_deps/include,$(shell $(PKG_CONFIG) --cflags libjpeg)) \
                  -I$(LIBRAW_DIR) -I$(LIBRAW_DIR)/libraw

APP_SRC  = src/main.c \
           src/app/apro_jobs.c \
           src/app/task.c \
           src/app/app_cli.c \
           src/app/app_settings.c \
           src/app/app_state.c \
           src/app/apro_paths.c \
           src/app/apro_font.c \
           src/app/ui_scale.c \
           src/app/workspace.c \
           src/app/lib_info.c \
           src/app/apro_download.c \
           src/catalog/catalog.c \
           src/edit/edit_params.c \
           src/input/shortcut.c \
           src/edit/edit_history.c \
           src/edit/wb_temp.c \
           src/edit/edit_auto.c \
           src/edit/edit_auto_run.c \
           src/cache/thumb_cache.c \
           src/export/export_settings.c \
           src/export/export_meta.c \
           src/export/export_write.c \
           src/export/export_icc.c \
           src/export/export_run.c \
           src/export/export_sheet.c \
           src/output/output_preset.c \
           src/output/proof.c \
           src/hdr/hdr_merge.c \
           src/stack/stack_source.c \
           src/stack/stack_measure.c \
           src/stack/stack_register.c \
           src/stack/stack_warp.c \
           src/stack/stack_drizzle.c \
           src/stack/stack_average.c \
           src/stack/stack_lucky.c \
           src/stack/stack_focus.c \
           src/stack/stack_cache.c \
           src/stack/stack_calib.c \
           src/stack/stack_deepsky.c \
           src/stack/stack_reject.c \
           src/stack/stack_ser.c \
           src/stack/stack_stars.c \
           src/stack/stack_video.c \
           src/archive/archive.c \
           src/cull/cull.c \
           src/timelapse/timelapse.c \
           src/timelapse/timelapse_run.c \
           src/import/import.c \
           src/accel/accel.c \
           src/accel/accel_opencl.c \
           src/model/model_runtime.c \
           src/model/model_store.c \
           src/model/model_mask.c \
           src/model/model_denoise.c src/model/model_seplut.c src/model/model_eyes.c \
           src/camera/camera_profile.c \
           src/camera/camera_fetch.c \
           src/camera/dcp.c \
           src/camera/camera_icc.c \
           src/lens/lens_profile.c \
           src/lens/lens_lensfun.c \
           src/meta/metadata.c \
           src/meta/xmp_sidecar.c \
           src/meta/meta_file.c \
           src/meta/meta_dump.c \
           src/plugin/plugin_host.c \
           src/preset/preset.c \
           src/sidecar/sidecar.c \
           src/raw/img_fits.c \
           src/raw/img_formats.c \
           src/raw/img_open.c \
           src/raw/raw_open.c \
           src/raw/raw_dng.c \
           src/raw/raw_probe.c \
           src/raw/raw_tags.c \
           src/raw/raw_thumb.c \
           src/pipe/pipe_image.c \
           src/pipe/pipe_graph.c \
           src/pipe/pipe_output.c \
           src/pipe/st_blacklevel.c \
           src/pipe/st_banding.c \
           src/pipe/st_whitebalance.c \
           src/pipe/st_demosaic.c \
           src/pipe/st_demosaic_rcd.c \
           src/pipe/st_demosaic_amaze.c \
           src/pipe/st_exposure.c \
           src/pipe/st_highlights.c \
           src/pipe/st_hlrebuild.c \
           src/pipe/st_defringe.c \
           src/pipe/st_lines.c \
           src/pipe/st_toneeq.c \
           src/pipe/st_curve.c \
           src/pipe/st_color.c \
           src/pipe/st_detail.c \
           src/pipe/st_stretch.c \
           src/pipe/st_lens.c \
           src/pipe/st_local.c \
           src/pipe/st_region.c \
           src/pipe/st_hsl.c \
           src/pipe/st_geometry.c \
           src/pipe/st_colorspace.c \
           src/ui/ui_browser.c \
           src/ui/ui_adjust.c \
           src/ui/ui_develop.c \
           src/ui/ui_export.c \
           src/ui/ui_shell.c \
           src/ui/ui_help.c \
           src/ui/help_data.c \
           src/ui/ui_shortcuts.c \
           src/ui/ui_tasks.c \
           src/ui/ui_paste.c \
           src/ui/ui_compare.c \
           src/ui/ui_import.c \
           src/ui/ui_sections.c \
           src/ui/ui_models.c \
           src/ui/ui_dnpreview.c src/ui/ui_hdr.c src/ui/ui_libs.c src/ui/ui_meta.c src/ui/ui_cull.c \
           src/ui/ui_gridmenu.c \
           src/ui/ui_timelapse.c src/ui/ui_stack.c \
           src/ui/ui_confirm.c \
           src/ui/ui_histogram.c \
           src/ui/ui_crop.c \
           src/ui/ui_output.c \
           src/ui/theme.c \
           src/platform/apro_platform.c

APP_OBJ   = $(patsubst src/%.c,$(OBJDIR)/%.o,$(APP_SRC))
NIL_OBJ   = $(patsubst $(NILOREA_DIR)/src/%.c,$(OBJDIR)/nil/%.o,$(NIL_SRC))
CJSON_OBJ = $(OBJDIR)/nil/cJSON.o
LIBRAW_LIB = $(OBJDIR)/libraw.a
OBJ       = $(APP_OBJ) $(NIL_OBJ) $(CJSON_OBJ) $(EXTRA_OBJ)
DEPS      = $(APP_OBJ:.o=.d) $(NIL_OBJ:.o=.d) $(CJSON_OBJ:.o=.d)

.PHONY: source-release check-licenses windows-deps all debug asan tsan clang clang-test asan-test tsan-test test bench camera-look fetch-samples plugins docs docs-api docs-html docs-pdf docs-serve \
        check-format portability windows windows-check windows-stage installer-windows clean distclean \
        deb appimage docker-build pkg-release-binary show-version bump-version

# The shipped plugins. They link nothing of the program: a plugin includes
# apro_plugin.h and that is the whole of its dependency on us, which is what
# makes the interface an interface rather than a habit.
# They are built into data/, which is where everything that ships beside the
# program lives and what the packaging targets copy.
# The cross build puts its DLLs in its own object directory instead, so that
# data/, which the Linux packages copy whole, never carries Windows plugins;
# `make windows` stages them beside the exe's data/ (windows-stage).
# They link the maths library themselves: before, a plugin calling expf found
# it in the program that loaded it, which held only while the program happened
# to call the same functions. A plugin using one the program did not failed to
# load with "undefined symbol".
PLUGIN_SRC = $(wildcard plugins/*.c)
PLUGIN_DIR = $(if $(filter 1,$(WINCROSS)),$(OBJDIR)/plugins,data/plugins)
PLUGIN_LIB = $(patsubst plugins/%.c,$(PLUGIN_DIR)/%$(PLUGIN_EXT),$(PLUGIN_SRC))

all: $(BUILD_BIN)$(EXE) $(PLUGIN_LIB)

plugins: $(PLUGIN_LIB)

# Never instrumented, whatever the build: data/plugins is shared by every
# build, and a release binary cannot load a plugin that needs a sanitizer's
# runtime. An instrumented binary loads an uninstrumented plugin fine.
# PLUGIN_RES is empty off Windows; there it is the plugin's version resource,
# the one object among the prerequisites.
$(PLUGIN_DIR)/%$(PLUGIN_EXT): plugins/%.c include/apro_plugin.h $(wildcard plugins/*.h) $(PLUGIN_RES)
	@mkdir -p $(PLUGIN_DIR)
	$(CC) $(WARN) $(OWN_WARN) -O3 -std=gnu17 $(PLUGIN_PIC) -shared -Iinclude -o $@ $< $(filter %.o,$^) -lm

$(BUILD_BIN)$(EXE): $(OBJ) $(LIBRAW_LIB)
	$(CC) -o $@ $^ $(LDFLAGS) $(WIN_SUBSYSTEM) $(LDLIBS) $(PLATFORM_LIBS)

$(LIBRAW_LIB): $(LIBRAW_OBJ)
	$(AR) rcs $@ $^

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

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

$(CJSON_OBJ): $(CJSON_SRC)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -MMD -MP -c -o $@ $<

$(OBJDIR)/libraw/%.o: $(LIBRAW_DIR)/src/%.cpp
	@mkdir -p $(dir $@)
	$(CXX) $(LIBRAW_CXXFLAGS) -c -o $@ $<

# The cross build's two libraries compiled from source (see WINCROSS above).
# Third-party, so without -Werror and with their warnings off, as LibRaw.
# The Little CMS plugins are left out: fast_float and threaded are optional
# and the proof does not use them.
$(OBJDIR)/sqlite3.o: $(MINGW_SQLITE)/sqlite3.c
	@mkdir -p $(dir $@)
	$(CC) -O2 -w -DSQLITE_THREADSAFE=1 -c -o $@ $<

LCMS2_SRC = $(wildcard $(MINGW_LCMS2)/src/*.c)
LCMS2_OBJ = $(patsubst $(MINGW_LCMS2)/src/%.c,$(OBJDIR)/lcms2/%.o,$(LCMS2_SRC))

$(OBJDIR)/lcms2.a: $(LCMS2_OBJ)
	$(AR) rcs $@ $^

$(OBJDIR)/lcms2/%.o: $(MINGW_LCMS2)/src/%.c
	@mkdir -p $(dir $@)
	$(CC) -O2 -w -I$(MINGW_LCMS2)/include -c -o $@ $<

# The program's icon, for Explorer, the taskbar and the installer's entry in
# Apps. Generated from the same SVG as the Linux icon, as a build product.
$(OBJDIR)/afterapro.ico: packaging/linux/afterapro.svg
	@mkdir -p $(dir $@)
	convert -background none $< -define icon:auto-resize=256,48,32,16 $@

# The version resource (packaging/windows/version.rc) goes into the exe with
# the icon and into each plugin alone. The four numbers are computed here:
# the resource compiler cannot split the text, and would read a part written
# 005 as octal. Both depend on the version header, so they follow a bump.
APRO_VERSION_RC := $(shell echo $(APRO_VERSION_STR) | awk -F. '{ printf "%d,%d,%d,0", $$1, $$2, $$3 }')

$(OBJDIR)/afterapro_res.o: packaging/windows/afterapro.rc packaging/windows/version.rc \
                           include/apro_version.h $(OBJDIR)/afterapro.ico
	$(WINDRES) -I$(OBJDIR) -Iinclude -DAPRO_RC_FILEVERSION=$(APRO_VERSION_RC) -o $@ $<

$(OBJDIR)/plugin_res/%.o: packaging/windows/version.rc include/apro_version.h
	@mkdir -p $(dir $@)
	$(WINDRES) -Iinclude -DAPRO_RC_FILEVERSION=$(APRO_VERSION_RC) -DAPRO_RC_DLL -DAPRO_RC_NAME=$* -o $@ $<

# No clean first: each of these has its own object directory, so switching
# between them costs a link rather than a full rebuild.
debug:
	$(MAKE) DEBUG=1 all

asan:
	$(MAKE) SAN=asan all

tsan:
	$(MAKE) SAN=tsan all

clang:
	$(MAKE) CLANG=1 all

# The whole suite, smoke test included, under each. `make test` is -O3 with no
# instrumentation, so it proves behaviour and nothing about memory or threads:
# a use after free that reads plausible bytes passes it every time.
# Every report stops the run: halt_on_error for UBSan, which otherwise only
# prints, and TSan's non-zero exit. The suppression files name third-party
# code only (drivers, the window system); a report in this program's code is
# fixed, not suppressed.
clang-test:
	$(MAKE) CLANG=1 test

# use_sigaltstack=0: the OpenCL runtime's threads replace the alternate signal
# stack ASan gives every thread, and ASan then fails to unmap its own when the
# thread ends and aborts the run. Measured on test_accel: 3 of 3 runs aborted
# without it, 0 of 3 with it.
asan-test:
	ASAN_OPTIONS=detect_leaks=1:strict_string_checks=1:detect_stack_use_after_return=1:use_sigaltstack=0 \
	LSAN_OPTIONS=suppressions=$(CURDIR)/tests/asan-suppressions.txt:print_suppressions=0 \
	UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 \
	$(MAKE) SAN=asan test

# report_destroy_locked=0: at exit, Allegro's al_uninstall_system() closes the
# X display and XCloseDisplay() destroys one of Xlib's own mutexes while it is
# locked. ThreadSanitizer aborts on that report with "nested bug in the same
# thread" before a suppression can apply, 3 runs out of 3; off, 0. It also
# stops a mutex of this program's being reported for the same thing, which is
# the price.
tsan-test:
	TSAN_OPTIONS=second_deadlock_stack=1:halt_on_error=1:report_destroy_locked=0:suppressions=$(CURDIR)/tests/tsan.supp \
	$(MAKE) SAN=tsan test

# --------------------------------------------------------------------------
# Tests. Unit tests link the pure modules only, so they run without a display.
# The smoke test needs one and skips itself cleanly when there is none.
# --------------------------------------------------------------------------
TEST_SRC = $(wildcard tests/test_*.c)
TEST_BIN = $(patsubst tests/%.c,$(TEST_OUT)/%.bin,$(TEST_SRC))
# Everything but main(), so a test can reach any module. The interface units
# link without a display: a test that does not call them costs nothing, and a
# test of their pure logic could not exist otherwise.
#
# Object files rather than sources. Listing the sources made every test binary
# compile the whole program again: twenty five tests against seventy units is
# seventeen hundred compilations to run a gate, and it was most of the wait.
# The objects are the same ones the program links, already built by the
# pattern rules above, so a test now costs one compilation and a link.
TEST_UNITS = $(filter-out $(OBJDIR)/main.o,$(OBJ))

# Benchmarks are not tests: they need a real photograph and they take seconds.
# `make bench` builds and runs them, and says where the time goes.
BENCH_SRC = $(wildcard tests/bench_*.c)
BENCH_BIN = $(patsubst tests/%.c,tests/%.bin,$(BENCH_SRC))

# One sample RAW file per format, from the list in tests/raw-samples.tsv, into
# samples/raw/ (not tracked). test_formats skips what is not there, so this is
# needed only to test the formats, not to run the suite.
fetch-samples:
	@sh tools/fetch-samples.sh tests/raw-samples.tsv samples/raw

# The mingw libraries windows-check compiles against and `make windows` links:
# Allegro's own mingw build and its dependencies, SQLite's amalgamation and
# Little CMS, each checked against its SHA-256. Without them, windows-check
# skips the files that include them and `make windows` stops and says so.
MINGW_DEPS_INC = $(foreach d,allegro/include allegro_deps/include sqlite-amalgamation-3530400 lcms2-2.17/include,\
                   $(if $(wildcard $(MINGW_DEPS_DIR)/$(d)),-idirafter $(MINGW_DEPS_DIR)/$(d)))

windows-deps:
	@sh tools/fetch-windows-deps.sh $(MINGW_DEPS_DIR)

bench: $(BENCH_BIN)
	@for b in $(BENCH_BIN); do echo "== $$b"; ./$$b || exit 1; done

# The tool that fits a camera profile's look table to the camera's own
# JPEGs (D309). Built only on demand, never by `make` or `make test`; see
# docs/user/camera-profiles.md for how it is run.
camera-look: tools/camera_look.bin

tools/%.bin: tools/%.c $(TEST_UNITS) $(LIBRAW_LIB)
	$(CC) $(CFLAGS) $(OWN_WARN) -o $@ $^ $(LDFLAGS) $(LDLIBS) $(PLATFORM_LIBS)

# -Werror here as for the program: the tests were built without it, and a
# shadowed variable and a possible truncation sat in two of them unseen.
$(TEST_OUT)/%.bin: tests/%.c $(TEST_UNITS) $(LIBRAW_LIB)
	@mkdir -p $(TEST_OUT)
	$(CC) $(CFLAGS) $(OWN_WARN) -o $@ $^ $(LDFLAGS) $(LDLIBS) $(PLATFORM_LIBS)

test: $(TEST_BIN) $(BUILD_BIN)$(EXE) $(PLUGIN_LIB)
	@for t in $(TEST_BIN); do echo "== $$t"; ./$$t || exit 1; done
	@sh tests/smoke.sh ./$(BUILD_BIN)$(EXE)

# --------------------------------------------------------------------------
# Documentation. Markdown is the source, everything else is generated.
# --------------------------------------------------------------------------
docs: docs-api docs-html docs-pdf

docs-api:
	@command -v $(DOXYGEN) >/dev/null 2>&1 || { echo "ERROR: doxygen not found"; exit 1; }
	$(DOXYGEN) Doxyfile
	@echo "API docs in docs/api/html"

DOC_MD  = $(wildcard docs/user/*.md) $(wildcard docs/dev/*.md)
DOC_HTML = $(patsubst docs/%.md,docs/build/html/%.html,$(DOC_MD))

docs-html: $(DOC_HTML)
	@echo "HTML docs in docs/build/html"

docs/build/html/%.html: docs/%.md
	@command -v $(PANDOC) >/dev/null 2>&1 || { echo "ERROR: pandoc not found"; exit 1; }
	@mkdir -p $(dir $@)
	$(PANDOC) --standalone --metadata title="$(notdir $*)" -f gfm -t html -o $@ $<

# A LaTeX engine is a large dependency, so a missing one is a clear message
# rather than a build failure.
docs-pdf:
	@command -v $(PANDOC) >/dev/null 2>&1 || { echo "ERROR: pandoc not found"; exit 1; }
	@if ! command -v pdflatex >/dev/null 2>&1 && ! command -v tectonic >/dev/null 2>&1; then \
		echo "SKIP: no LaTeX engine found, docs-pdf produces nothing"; exit 0; \
	fi
	@mkdir -p docs/build/pdf
	@for f in $(DOC_MD); do \
		out=docs/build/pdf/`basename $$f .md`.pdf; \
		$(PANDOC) -f gfm -o $$out $$f || exit 1; \
	done
	@echo "PDF docs in docs/build/pdf"

docs-serve: docs-html
	@echo "serving docs/build/html on http://localhost:8080"
	@cd docs/build/html && python3 -m http.server 8080

# --------------------------------------------------------------------------
# Formatting and static analysis
# --------------------------------------------------------------------------

# The documentation the help window carries. Regenerated whenever a page under
# docs/user changes, so the window can never be showing a version of the
# documentation the repository has moved past.
HELP_SRC = $(wildcard docs/user/*.md)

src/ui/help_data.c: $(HELP_SRC) tools/mkhelp.sh
	sh tools/mkhelp.sh docs/user $@

# The file types the Windows installer registers, generated from the same
# table the browser and the open dialog read. The installer used to name eight
# extensions by hand and the table moved to forty six without it, which is the
# drift one table was supposed to end. It is a prerequisite of the two targets
# that care about Windows rather than of `all`, because a stale list is a
# packaging problem and not a reason a Linux build should stop.
ASSOC_NSH = packaging/windows/associations.nsh

$(ASSOC_NSH): src/raw/img_formats.c tools/mkassoc.sh
	sh tools/mkassoc.sh $< $@

# Every header, public and private. The ones under src/ were left out of the
# check until a drifted one was found there, which is the argument for a
# wildcard rather than a list: a header added tomorrow is covered without
# anybody remembering to add it.
ALL_HDR = $(wildcard include/*.h) $(wildcard src/*/*.h)

# The complete source of a release (DISTRIBUTION.md item 1): AfterAPro and
# nilorea-library at the commits built, in one tarball that builds on its
# own with `make NILOREA_DIR=nilorea-library`. A GPL binary has to come with,
# or point at, all of its source, and nilorea is compiled into it. Only
# committed work goes in: a tree with uncommitted changes is refused, so the
# tarball is exactly the commits SOURCE-RELEASE.txt names.
SRC_STAGE   = $(DIST_DIR)/src-release/afterapro-$(PKG_VERSION)
SRC_RELEASE = $(DIST_DIR)/afterapro-$(PKG_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
source-release:
	@git diff --quiet HEAD -- && git -C $(NILOREA_DIR) diff --quiet HEAD -- || { \
		echo "ERROR: commit AfterAPro 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 $(NILOREA_DIR) archive --format=tar HEAD | tar -x $(SRC_EXCLUDE) -C "$(SRC_STAGE)/nilorea-library"
	printf 'AfterAPro %s, commit %s\nnilorea-library, commit %s\n\nBuild with: make NILOREA_DIR=nilorea-library\n' \
	    "$(PKG_VERSION)" "`git rev-parse HEAD`" "`git -C $(NILOREA_DIR) rev-parse HEAD`" > "$(SRC_STAGE)/SOURCE-RELEASE.txt"
	tar -C "$(DIST_DIR)/src-release" -czf "$(SRC_RELEASE)" "afterapro-$(PKG_VERSION)"
	@echo "Built $(SRC_RELEASE)"

# THIRD_PARTY_LICENSES against the licence files it is made from
# (DISTRIBUTION.md item 6); tools/gen_third_party_licenses.py rewrites it.
check-licenses:
	python3 tools/gen_third_party_licenses.py --check

check-format:
	@command -v clang-format >/dev/null 2>&1 || { echo "ERROR: clang-format not found"; exit 1; }
	clang-format --dry-run --Werror $(APP_SRC) $(ALL_HDR) $(TEST_SRC)
	@command -v clang-tidy >/dev/null 2>&1 || { echo "ERROR: clang-tidy not found"; exit 1; }
	clang-tidy $(APP_SRC) -- $(CFLAGS)

# --------------------------------------------------------------------------
# Portability sweep. Runs anywhere, needs no cross toolchain, and enforces
# the rule that only src/platform may know which operating system it is on.
# --------------------------------------------------------------------------
portability:
	@bad=`grep -rnE '(#if(n?def)? *_WIN32|#if(n?def)? *__linux__|<unistd\.h>|<sys/|<pthread\.h>|\bfork *\(|\bdlopen *\()' \
	         src include --include='*.c' --include='*.h' \
	         | grep -v '^src/platform/' || true`; \
	if [ -n "$$bad" ]; then \
		echo "ERROR: platform specific code outside src/platform (CLAUDE.md 1.4):"; \
		echo "$$bad"; \
		exit 1; \
	fi
	@echo "portability: no platform specific code outside src/platform"

# --------------------------------------------------------------------------
# Windows build. On MSYS2/mingw64 plain `make` is the Windows build; this
# target is the cross build from Linux, attempted at the end of every
# milestone so portability breaks surface one at a time rather than all at
# once at M10. It needs a mingw Allegro, which a Linux distribution does not
# ship: the message says so instead of failing with a missing header.
# --------------------------------------------------------------------------
# Compile every translation unit that does not need a library this machine
# lacks a mingw build of, with the Windows compiler and the Windows warnings.
# It is not a build and produces nothing; what it catches is the code that
# only the other platform compiles, which is otherwise never seen until
# somebody has an MSYS2 shell open. Roughly half the tree goes through it,
# including the whole pipeline and all of src/platform.
windows-check: $(ASSOC_NSH)
	@command -v $(WINDOWS_CC) >/dev/null 2>&1 || { \
		echo "ERROR: $(WINDOWS_CC) not found, install the mingw-w64 toolchain"; exit 1; }
	@ok=0; skipped=0; bad=0; \
	for f in $(filter-out src/main.c,$(APP_SRC)) $(PLUGIN_SRC); do \
		out=`$(WINDOWS_CC) $(WARN) -std=gnu17 -D_GNU_SOURCE -DHAVE_ALLEGRO -DHAVE_CJSON \
		        -DENABLE_LOCALES -D__USE_MINGW_ANSI_STDIO=1 -Iinclude \
		        -I$(abspath $(NILOREA_DIR))/include \
		        -I$(abspath $(NILOREA_DIR))/external/cJSON -I$(LIBRAW_DIR) -Iexternal/onnxruntime \
		        $(MINGW_DEPS_INC) -fsyntax-only $$f 2>&1`; \
		if echo "$$out" | grep -q 'No such file\|Aucun fichier'; then \
			skipped=`expr $$skipped + 1`; \
		elif [ -n "$$out" ]; then \
			echo "$$out"; bad=`expr $$bad + 1`; \
		else ok=`expr $$ok + 1`; fi; \
	done; \
	echo "windows-check: $$ok clean, $$skipped skipped for want of a mingw library, $$bad with problems"; \
	if [ $$skipped -gt 0 ] && [ -z "$(MINGW_DEPS_INC)" ]; then \
		echo "windows-check: make windows-deps fetches the mingw headers the skipped files need"; fi; \
	test $$bad -eq 0

windows: portability windows-check
	@for tool in $(WINCROSS_CC) $(WINCROSS_CXX) x86_64-w64-mingw32-windres convert; do \
		command -v $$tool >/dev/null 2>&1 || { echo "ERROR: $$tool not found. Debian:"; \
		echo "       sudo apt install gcc-mingw-w64-x86-64-posix g++-mingw-w64-x86-64-posix imagemagick"; exit 1; }; done
	@test -d $(MINGW_DEPS_DIR)/allegro/lib -a -f $(MINGW_SQLITE)/sqlite3.c -a -d $(MINGW_LCMS2)/src || { \
		echo "ERROR: the mingw libraries are not in $(MINGW_DEPS_DIR). make windows-deps"; \
		echo "       fetches them, once. On MSYS2, plain make is the Windows build."; exit 1; }
	$(MAKE) WINCROSS=1 all
	$(MAKE) --no-print-directory WINCROSS=1 windows-stage

# What goes to a Windows machine, in one folder: the exe, the DLLs it and its
# plugins need, data/ with the Windows plugins in it, and the licences. The
# installer packs this folder; zipped, it is also a build that runs from
# wherever it is unpacked. Works on MSYS2 as well as for the cross build: the
# DLLs are looked for beside the compiler, in the gcc runtime's directory and
# in the Allegro release, and tools/windows-dlls.sh fails on any it cannot
# find rather than letting the program fail to start somewhere else.
WIN_STAGE    = $(DIST_DIR)/windows/AfterAPro
WIN_OBJDUMP  = $(if $(filter 1,$(WINCROSS)),x86_64-w64-mingw32-objdump,objdump)
WIN_STRIP    = $(if $(filter 1,$(WINCROSS)),x86_64-w64-mingw32-strip,strip)
WIN_DLL_PATH = $(MINGW_DEPS_DIR)/allegro/bin:$(dir $(shell $(CC) -print-libgcc-file-name)):$(dir $(shell $(CC) -print-file-name=libwinpthread-1.dll)):$(dir $(shell command -v $(CC)))
WIN_SYSLIB   = $(dir $(shell $(CC) -print-file-name=libkernel32.a))
# Self-signed Authenticode signatures (tools/windows-sign.sh). auto signs when
# osslsigncode and the key are both on the machine and says so when they are
# not; 1 fails without them, which is what a release wants; 0 signs nothing.
# The certificate goes into the folder beside the exe, for whoever wants to
# trust the publisher.
# WIN_SIGN_FINGERPRINT is the SHA-256 of that certificate, the one README.md
# gives. A build whose key is another one stops rather than sign as a second
# NiloreaStudio; empty accepts whatever key is there.
WIN_SIGN    ?= auto
WIN_SIGN_CER = NiloreaStudio.cer
WIN_SIGN_FINGERPRINT ?= b9976986aebbfa925b019ee453d9834549b03581fd6ffa28c68f88e6df4a6acd
WIN_SIGN_ENV = WINSIGN_FINGERPRINT="$(WIN_SIGN_FINGERPRINT)" WINSIGN_PRODUCT=AfterAPro

windows-stage: $(BINARY).exe $(PLUGIN_LIB) $(OBJDIR)/afterapro.ico
	rm -rf "$(WIN_STAGE)"
	install -d "$(WIN_STAGE)/data/plugins"
	install -m 0755 $(BINARY).exe "$(WIN_STAGE)/"
	install -m 0644 $(OBJDIR)/afterapro.ico "$(WIN_STAGE)/../"
	tar -C data --exclude=./plugins -cf - . | tar -C "$(WIN_STAGE)/data" -xf -
	cp $(PLUGIN_LIB) "$(WIN_STAGE)/data/plugins/"
	$(call apro_stage_licenses,$(WIN_STAGE)/licenses)
	@if [ -f $(MINGW_LCMS2)/LICENSE ]; then install -m 0644 $(MINGW_LCMS2)/LICENSE "$(WIN_STAGE)/licenses/lcms2-LICENSE"; fi
	install -m 0644 $(INSTALLER_DIR)/NOTICES.txt "$(WIN_STAGE)/licenses/NOTICES.txt"
	@# The terms of the GCC runtime DLLs, of winpthreads and of the mingw-w64
	@# runtime are sections of THIRD_PARTY_LICENSES, from packaging/licenses,
	@# whatever machine builds the folder (D383).
	sh tools/windows-dlls.sh $(WIN_OBJDUMP) "$(WIN_DLL_PATH)" "$(WIN_SYSLIB)" "$(WIN_STAGE)" \
	   "$(WIN_STAGE)/$(BINARY).exe" $(PLUGIN_LIB)
	@# The toolchain's libstdc++ carries its debugging symbols: 29 MB of the
	@# 54 MB the folder held before this, 16 after.
	@# The plugins too: theirs is four fifths of each file, and a DLL
	@# carrying DWARF sections is one more thing a malware scanner finds
	@# unusual.
	$(WIN_STRIP) --strip-unneeded "$(WIN_STAGE)"/*.dll "$(WIN_STAGE)"/data/plugins/*.dll \
	             "$(WIN_STAGE)/$(BINARY).exe"
	@# Signed last: strip rewrites a file and the signature covers it. Every
	@# exe and DLL in the folder, the ones we did not build included: one
	@# unsigned DLL is what a rule on the publisher stops at.
	$(WIN_SIGN_ENV) sh tools/windows-sign.sh $(WIN_SIGN) --cert-out "$(WIN_STAGE)/$(WIN_SIGN_CER)" \
	   "$(WIN_STAGE)/$(BINARY).exe" "$(WIN_STAGE)"/*.dll "$(WIN_STAGE)"/data/plugins/*.dll
	@echo "windows: $(WIN_STAGE)"

# The installer. NSIS is the one that cross compiles: makensis runs on Linux
# and produces a Windows installer, so this target works from either side.
NSIS          ?= makensis
INSTALLER_DIR  = packaging/windows
INSTALLER_OUT  = dist/$(BINARY)-$(APRO_VERSION_STR)-setup.exe

installer-windows: $(ASSOC_NSH)
	@command -v $(NSIS) >/dev/null 2>&1 || { \
		echo "ERROR: $(NSIS) not found."; \
		echo "       Debian: sudo apt install nsis   MSYS2: pacman -S mingw-w64-x86_64-nsis"; \
		exit 1; }
	@test -f $(WIN_STAGE)/$(BINARY).exe || { \
		echo "ERROR: $(WIN_STAGE) is not there. Run make windows from Linux, or"; \
		echo "       make and make windows-stage on MSYS2, before the installer."; \
		exit 1; }
	@mkdir -p dist
	@# APRO_SIGN has makensis sign the uninstaller it writes into the
	@# installer, which is the only moment that file exists outside one
	@# (afterapro.nsi). The script reads its settings from the environment.
	$(WIN_SIGN_ENV) $(NSIS) -NOCD -V2 -DAPRO_VERSION=$(APRO_VERSION_STR) \
	        $(if $(filter 0,$(WIN_SIGN)),,-DAPRO_SIGN=$(WIN_SIGN)) \
	        -DAPRO_STAGE=$(WIN_STAGE) -DAPRO_OUT=$(INSTALLER_OUT) $(INSTALLER_DIR)/afterapro.nsi
	$(WIN_SIGN_ENV) sh tools/windows-sign.sh $(WIN_SIGN) $(INSTALLER_OUT)
	@echo "installer: $(INSTALLER_OUT)"

# --------------------------------------------------------------------------
# Linux packaging: .deb, AppImage, and both built in a Debian container.
# Adapted from Fissure's and Sketchr's (docs/dev/AUDIT.md 3.2). The program
# finds data/ next to its own executable (apro_paths_resource), so both
# packages keep the two together: /opt/afterapro in the .deb, usr/bin in the
# AppImage. No version bump: the version is APRO_VERSION_STR, which moves
# only with make bump-version, and PKG_VERSION= overrides it for one run, as
# docker-build does to add the Debian codename.
# --------------------------------------------------------------------------
LINUX_PKG      = packaging/linux
DIST_DIR       = dist
PKG_VERSION   ?= $(APRO_VERSION_STR)
DEB_ARCH      ?= $(shell dpkg --print-architecture 2>/dev/null || echo amd64)
DEB_ROOT       = $(DIST_DIR)/deb/afterapro_$(PKG_VERSION)_$(DEB_ARCH)
DEB_FILE       = $(DIST_DIR)/afterapro_$(PKG_VERSION)_$(DEB_ARCH).deb
APPDIR         = $(DIST_DIR)/AfterAPro.AppDir
APPIMAGE_FILE  = $(DIST_DIR)/AfterAPro-$(PKG_VERSION)-x86_64.AppImage
APPIMAGETOOL  ?= $(DIST_DIR)/appimagetool-x86_64.AppImage
APPIMAGETOOL_URL = https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
# Generated from the SVG rather than committed: it is a build product.
APPICON        = $(DIST_DIR)/afterapro-256.png

# AfterAPro's own licence, GPLv3 since the RCD and AMaZE ports (D204), and
# the third-party notices that travel with every package. The DejaVu one is
# already under data/fonts/LICENSES and goes with data/.
define apro_stage_licenses
	install -d "$(1)"
	install -m 0644 LICENSE "$(1)/AfterAPro-LICENSE"
	install -m 0644 NOTICE "$(1)/AfterAPro-NOTICE"
	install -m 0644 THIRD_PARTY_LICENSES "$(1)/THIRD_PARTY_LICENSES"
	install -m 0644 $(LIBRAW_DIR)/COPYRIGHT "$(1)/LibRaw-COPYRIGHT"
	install -m 0644 $(LIBRAW_DIR)/LICENSE.LGPL "$(1)/LibRaw-LICENSE.LGPL"
	install -m 0644 $(LIBRAW_DIR)/LICENSE.CDDL "$(1)/LibRaw-LICENSE.CDDL"
	install -m 0644 $(NILOREA_DIR)/LICENSE "$(1)/nilorea-LICENSE"
	install -m 0644 $(NILOREA_DIR)/NOTICE "$(1)/nilorea-NOTICE"
	install -m 0644 $(NILOREA_DIR)/external/cJSON/LICENSE "$(1)/cJSON-LICENSE"
endef

# The binary and the plugins share their name with the instrumented builds:
# `make debug` links an ASan afterapro over the release one, and `all` then
# sees it as up to date. Packaging that would ship a program that needs
# libasan to start. Whatever names a sanitizer runtime is removed and relinked
# from the release objects, which costs a link rather than a build.
pkg-release-binary:
	@for f in $(BINARY) $(PLUGIN_LIB); do \
		if [ -f "$$f" ] && readelf -d "$$f" | grep -q 'NEEDED.*lib[atu]*san'; then \
			echo "$$f is an instrumented build, relinking it for packaging"; \
			rm -f "$$f"; \
		fi; \
	done
	$(MAKE) --no-print-directory all

$(APPICON): $(LINUX_PKG)/afterapro.svg
	@mkdir -p $(dir $@)
	rsvg-convert -w 256 -h 256 -o $@ $< 2>/dev/null \
	    || convert -background none $< -resize 256x256 $@

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

# A .deb for the distribution it is built on. It depends on that
# distribution's libraries rather than carrying them; deb-depends.sh asks dpkg
# which package owns each library the binary and the plugins name. The
# launcher in /usr/bin is a relative symlink: Allegro resolves the resources
# path through /proc/self/exe, so the program still finds /opt/afterapro/data.
deb: pkg-release-binary $(APPICON)
	@command -v dpkg-deb >/dev/null 2>&1 || { echo "ERROR: dpkg-deb not found (install dpkg)"; exit 1; }
	rm -rf "$(DIST_DIR)/deb"
	install -d "$(DEB_ROOT)/opt/afterapro" "$(DEB_ROOT)/usr/bin" "$(DEB_ROOT)/DEBIAN" \
	           "$(DEB_ROOT)/usr/share/applications" \
	           "$(DEB_ROOT)/usr/share/icons/hicolor/256x256/apps" \
	           "$(DEB_ROOT)/usr/share/icons/hicolor/scalable/apps"
	install -m 0755 $(BINARY) "$(DEB_ROOT)/opt/afterapro/$(BINARY)"
	cp -r data "$(DEB_ROOT)/opt/afterapro/data"
	$(call apro_stage_licenses,$(DEB_ROOT)/opt/afterapro/licenses)
	ln -s ../../opt/afterapro/$(BINARY) "$(DEB_ROOT)/usr/bin/$(BINARY)"
	install -m 0644 $(LINUX_PKG)/afterapro.desktop "$(DEB_ROOT)/usr/share/applications/afterapro.desktop"
	install -m 0644 $(APPICON) "$(DEB_ROOT)/usr/share/icons/hicolor/256x256/apps/afterapro.png"
	install -m 0644 $(LINUX_PKG)/afterapro.svg "$(DEB_ROOT)/usr/share/icons/hicolor/scalable/apps/afterapro.svg"
	install -m 0755 $(LINUX_PKG)/deb-postinst "$(DEB_ROOT)/DEBIAN/postinst"
	install -d "$(DEB_ROOT)/usr/share/doc/afterapro"
	install -m 0644 $(LINUX_PKG)/deb-copyright "$(DEB_ROOT)/usr/share/doc/afterapro/copyright"
	deps=`sh $(LINUX_PKG)/deb-depends.sh $(BINARY) $(PLUGIN_LIB)` || exit 1; \
	size=`du -sk "$(DEB_ROOT)/opt" "$(DEB_ROOT)/usr" | awk '{s += $$1} END {print s}'`; \
	sed -e 's/@VERSION@/$(PKG_VERSION)/' -e 's/@ARCH@/$(DEB_ARCH)/' \
	    -e "s/@SIZE@/$$size/" -e "s/@DEPENDS@/$$deps/" \
	    $(LINUX_PKG)/deb-control.in > "$(DEB_ROOT)/DEBIAN/control"
	dpkg-deb --build --root-owner-group "$(DEB_ROOT)" "$(DEB_FILE)"
	@echo "Built $(DEB_FILE)"

# A self-contained AppImage: the binary, data/, and every library it needs
# that is not on the excludelist (glibc, the GL and driver stack, X11 and GTK
# stay the host's). lensfun is bundled but its lens database is not: it is
# looked up where the host keeps it, and without one the program corrects
# lenses from its own profiles, as a build without lensfun does.
appimage: pkg-release-binary $(APPICON) $(APPIMAGETOOL)
	rm -rf "$(APPDIR)"
	install -d "$(APPDIR)/usr/bin" "$(APPDIR)/usr/share/applications" \
	           "$(APPDIR)/usr/share/icons/hicolor/256x256/apps"
	install -m 0755 $(BINARY) "$(APPDIR)/usr/bin/$(BINARY)"
	cp -r data "$(APPDIR)/usr/bin/data"
	$(call apro_stage_licenses,$(APPDIR)/usr/share/doc/afterapro)
	sh $(LINUX_PKG)/bundle-libs.sh "$(APPDIR)/usr/bin/$(BINARY)" "$(APPDIR)" $(LINUX_PKG)/appimage-excludelist.txt \
	   "$(APPDIR)/usr/share/doc/afterapro/third-party"
	install -m 0755 $(LINUX_PKG)/AppRun "$(APPDIR)/AppRun"
	install -m 0644 $(LINUX_PKG)/afterapro.desktop "$(APPDIR)/afterapro.desktop"
	install -m 0644 $(LINUX_PKG)/afterapro.desktop "$(APPDIR)/usr/share/applications/afterapro.desktop"
	install -m 0644 $(APPICON) "$(APPDIR)/afterapro.png"
	install -m 0644 $(APPICON) "$(APPDIR)/.DirIcon"
	install -m 0644 $(APPICON) "$(APPDIR)/usr/share/icons/hicolor/256x256/apps/afterapro.png"
	ARCH=x86_64 "$(APPIMAGETOOL)" --appimage-extract-and-run "$(APPDIR)" "$(APPIMAGE_FILE)"
	@echo "Built $(APPIMAGE_FILE)"

# The release build: both packages made inside a debian:trixie-slim
# container, named with the codename. BASE_IMAGE=debian:bookworm-slim targets
# an older release. Needs docker. See packaging/linux/docker-build.sh.
docker-build:
	NILOREA_DIR="$(abspath $(NILOREA_DIR))" sh $(LINUX_PKG)/docker-build.sh

clean:
	rm -rf obj obj-debug obj-asan obj-tsan obj-clang obj-clang-* obj-win $(BINARY) $(BINARY).exe \
	       $(BINARY)-debug $(BINARY)-asan $(BINARY)-tsan $(BINARY)-clang $(BINARY)-clang-* tests/*.bin tools/*.bin \
	       data/plugins

distclean: clean
	rm -rf docs/api docs/build dist

-include $(DEPS)
