# betterx tools: faceshowx keyshowx zoomx cpickx handrollerx renamex fmanx  (+ faceshowx plugins)
#
#   make                          build every tool whose .c file is present
#   make TOOLS="zoomx cpickx"     build only these
#   sudo make install [TOOLS=..]  install what was built to /usr/local/bin (PREFIX=/usr to change); also makes
#   sudo make install ICONSTYLE=classic   system icon theme in the Windows XP style (users: handrollerx --icons classic)
#   make plugins                  build the faceshowx plugins (build/plugins/*.so)
#   make install-plugins          as YOUR user, not root: copy them to ~/.config/betterx/plugins
#   make integrate [FM=thunar]    as YOUR user: right-click entries for the file managers found (or FM=)
#   make unintegrate [FM=..]      take them out again   (FM: auto all thunar nautilus nemo caja dolphin pcmanfm ranger lf)
#   make clean
#
# Modular: a tool is built when it is wanted (TOOLS, default all) AND its .c file
# is in this directory AND its libraries are installed.  Anything that is left out
# is reported at the end with the reason - delete a .c file, or pass TOOLS=, to
# drop a tool; a missing library only skips that one tool instead of failing.
# betterx.h is shared and must stay.
#
# Libraries (pkg-config names):
#   zoomx, cpickx : x11 xrender xext xrandr   (cpickx: pangocairo optional, gives the classic theme a real font)
#   faceshowx     : x11 xext xrandr xcursor cairo, linux/videodev2.h, optional libjpeg(-turbo)
#   keyshowx      : x11 xcb xext xi xrandr cairo cairo-xlib pangocairo xkbcommon xkbcommon-x11
#                   (Gentoo: libxkbcommon needs USE="X")
#   renamex       : x11 xrandr xcb cairo pangocairo xkbcommon xkbcommon-x11   (the built-in menu)
#   handrollerx   : the same + libarchive (Gentoo: app-arch/libarchive)
#   faceshowx also links faceshowx-plugins/host/fsx_plugins.c and -ldl (plugin loader)
# libjpeg only adds MJPEG to faceshowx; force it off with:  make NOJPEG=1

CC      ?= gcc
CFLAGS  ?= -O2 -Wall -Wextra
PREFIX  ?= /usr/local

# Window icons (_NET_WM_ICON) are compiled in, both styles; each tool's `icon_style` config key picks one.
# ICONSTYLE is the style installed into the icon theme (app menus, right-click entries); users switch it with
# `handrollerx --icons modern|classic`, which needs the copies in PREFIX/share/betterx/icons.
ICONSTYLE ?= modern

ALL_TOOLS := faceshowx keyshowx zoomx cpickx handrollerx renamex fmanx
TOOLS     ?= $(ALL_TOOLS)

faceshowx_PKGS := x11 xext xrandr xcursor cairo
faceshowx_LIBS := -lm -ldl
faceshowx_SRCS := faceshowx-plugins/host/fsx_plugins.c
faceshowx_CF   := -I. -Ifaceshowx-plugins/include -Ifaceshowx-plugins/host
faceshowx_DEPS := $(wildcard faceshowx-plugins/host/* faceshowx-plugins/include/*)
keyshowx_PKGS  := x11 xcb xext xi xrandr cairo cairo-xlib pangocairo xkbcommon xkbcommon-x11
keyshowx_LIBS  := -lm
zoomx_PKGS     := x11 xrender xext xrandr
cpickx_PKGS    := x11 xrender xext xrandr
MENU_PKGS      := x11 xrandr xcb cairo pangocairo xkbcommon xkbcommon-x11
renamex_PKGS   := $(MENU_PKGS)
renamex_DEPS   := bx_menu.h bx_tool.h
renamex_CF     := -std=gnu11 -Wno-format-truncation
fmanx_PKGS     :=
fmanx_DEPS     := bx_tool.h fmanx_core.h fmanx_tui.h fmanx_cmd.h
fmanx_CF       := -std=gnu11 -Wno-format-truncation
handrollerx_PKGS := $(MENU_PKGS) libarchive
handrollerx_DEPS := bx_menu.h bx_tool.h bx_fm.h
handrollerx_CF   := -std=gnu11 -Wno-format-truncation

# optional pangocairo for cpickx: the classic theme then draws its text with a real font
ifeq ($(shell pkg-config --exists pangocairo && echo yes),yes)
cpickx_PKGS += pangocairo
cpickx_DEFS := -DHAVE_PANGO
endif

# optional libjpeg for faceshowx
ifneq ($(NOJPEG),1)
ifeq ($(shell pkg-config --exists libjpeg && echo yes),yes)
faceshowx_PKGS += libjpeg
faceshowx_DEFS := -DHAVE_JPEG
endif
endif

# --- which tools can actually be built -------------------------------------
REQ     := $(filter $(ALL_TOOLS),$(TOOLS))
UNKNOWN := $(filter-out $(ALL_TOOLS),$(TOOLS))
NOTREQ  := $(filter-out $(REQ),$(ALL_TOOLS))
HAVESRC := $(foreach t,$(REQ),$(if $(wildcard $(t).c),$(t)))
NOSRC   := $(filter-out $(HAVESRC),$(REQ))

missing_pkgs = $(foreach p,$($(1)_PKGS),$(if $(shell pkg-config --exists $(p) && echo y),,$(p)))
# the V4L2 header is not a pkg-config package
missing_hdr  = $(if $(filter faceshowx,$(1)),$(if $(shell echo '\#include <linux/videodev2.h>' | $(CC) -E -x c - >/dev/null 2>&1 && echo y),,linux/videodev2.h))
missing      = $(strip $(call missing_pkgs,$(1)) $(call missing_hdr,$(1)))

BUILD   := $(foreach t,$(HAVESRC),$(if $(call missing,$(t)),,$(t)))
NODEP   := $(filter-out $(BUILD),$(HAVESRC))

.PHONY: all install install-icons install-launchers clean summary plugins install-plugins integrate unintegrate
.SECONDEXPANSION:

all: $(BUILD) summary

$(BUILD): %: %.c betterx.h bx_icon.h bx_icons.h $$(%_DEPS)
	$(CC) $(CFLAGS) $($@_CF) $($@_DEFS) -o $@ $< $($@_SRCS) $$($(if $($@_PKGS),pkg-config --cflags --libs $($@_PKGS),true)) $($@_LIBS)

summary: $(BUILD)
	@echo
	@echo "betterx build summary"
	@for t in $(BUILD); do echo "  built      $$t"; done
	@for t in $(NOSRC); do echo "  NOT built  $$t   (no $$t.c here)"; done
	@$(foreach t,$(NODEP),echo "  NOT built  $(t)   (missing: $(call missing,$(t)))";)
	@for t in $(NOTREQ); do echo "  skipped    $$t   (not in TOOLS)"; done
	@for t in $(UNKNOWN); do echo "  warning: unknown tool '$$t' in TOOLS (known: $(ALL_TOOLS))"; done
	@$(if $(findstring faceshowx,$(BUILD)),$(if $(faceshowx_DEFS),,echo "  note: faceshowx built WITHOUT MJPEG (no libjpeg, or NOJPEG=1): YUYV only";))
	@$(if $(BUILD),,echo "  nothing was built!"; exit 1)
	@echo

install: all
	@$(if $(BUILD),,echo "nothing to install"; exit 1)
	@for t in $(BUILD); do install -Dm755 $$t $(DESTDIR)$(PREFIX)/bin/$$t && echo "installed $(DESTDIR)$(PREFIX)/bin/$$t"; done
	@$(MAKE) --no-print-directory install-icons
	@echo "per-user steps (run as yourself, not root): make install-plugins, make integrate"

# Icons: icons/modern (flat, dark tile) or icons/classic (glossy Windows XP style), one SVG per tool, into the
# hicolor theme.  /usr/share, not /usr/local/share: some systems (Gentoo) leave /usr/local/share out of
# XDG_DATA_DIRS, so icons there would never be found.   sudo make install ICONSTYLE=classic
ICONDIR   ?= /usr/share/icons/hicolor/scalable/apps
install-icons: install-launchers
	@for st in modern classic; do for t in $(BUILD) $(if $(findstring handrollerx,$(BUILD)),handrollerx-extract handrollerx-extractto handrollerx-compress); do if [ -f icons/$$st/$$t.svg ]; then install -Dm644 icons/$$st/$$t.svg $(DESTDIR)$(PREFIX)/share/betterx/icons/$$st/$$t.svg; fi; done; done; echo "installed both icon styles to $(DESTDIR)$(PREFIX)/share/betterx/icons (for handrollerx --icons)"
	@for t in $(BUILD) $(if $(findstring handrollerx,$(BUILD)),handrollerx-extract handrollerx-extractto handrollerx-compress); do if [ -f icons/$(ICONSTYLE)/$$t.svg ]; then install -Dm644 icons/$(ICONSTYLE)/$$t.svg $(DESTDIR)$(ICONDIR)/$$t.svg && echo "installed $(DESTDIR)$(ICONDIR)/$$t.svg"; fi; done
	@if [ -z "$(DESTDIR)" ] && command -v gtk-update-icon-cache >/dev/null 2>&1; then gtk-update-icon-cache -q -f -t $(dir $(patsubst %/,%,$(dir $(ICONDIR)))) 2>/dev/null || true; fi

# Launchers (.desktop) for every tool: app menus and panels match a running window to its launcher by
# StartupWMClass and take the icon from it.  Goes to /usr/share/applications (APPDIR).
APPDIR ?= /usr/share/applications
LAUNCH_zoomx      := Zoomx|Magnifier and screen-zoom|Zoom into the screen|Utility;
LAUNCH_cpickx     := Cpickx|Colour picker|Pick colours from anywhere on the screen|Graphics;Utility;
LAUNCH_keyshowx   := keyshowx|Key overlay|Show the keys you press on screen|Utility;
LAUNCH_faceshowx  := faceshowx|Webcam overlay|Show a webcam on the screen|AudioVideo;Video;Utility;
LAUNCH_renamex    := bx_menu|Bulk rename|Rename many files at once|Utility;FileTools;
LAUNCH_fmanx      := fmanx|File manager|Browse and manage files (terminal)|System;FileTools;FileManager;
install-launchers:
	@install -d $(DESTDIR)$(APPDIR); \
	for t in $(filter-out handrollerx,$(BUILD)); do spec="$(LAUNCH_$$t)"; \
	  case $$t in zoomx) spec="$(LAUNCH_zoomx)";; cpickx) spec="$(LAUNCH_cpickx)";; keyshowx) spec="$(LAUNCH_keyshowx)";; faceshowx) spec="$(LAUNCH_faceshowx)";; renamex) spec="$(LAUNCH_renamex)";; fmanx) spec="$(LAUNCH_fmanx)";; esac; \
	  cls=$${spec%%|*}; r=$${spec#*|}; nm=$${r%%|*}; r=$${r#*|}; cm=$${r%%|*}; cat=$${r#*|}; \
	  printf '[Desktop Entry]\nType=Application\nName=%s\nComment=%s\nExec=$(PREFIX)/bin/%s\nIcon=%s\nTerminal=false\nCategories=%s\nStartupWMClass=%s\n' "$$nm" "$$cm" $$t $$t "$$cat" $$cls > $$t.desktop.tmp; \
	  if [ $$t = fmanx ]; then sed -i 's|^Exec=.*|Exec=$(PREFIX)/bin/fmanx %F|; s|^Terminal=false|Terminal=true|; /^StartupWMClass/d' $$t.desktop.tmp; fi; \
	  if [ $$t = renamex ]; then sed -i 's|^Exec=.*|Exec=$(PREFIX)/bin/renamex %F|; /^StartupWMClass/d' $$t.desktop.tmp; fi; \
	  install -m644 $$t.desktop.tmp $(DESTDIR)$(APPDIR)/$$t.desktop && echo "installed $(DESTDIR)$(APPDIR)/$$t.desktop"; rm -f $$t.desktop.tmp; \
	done
	@if [ -z "$(DESTDIR)" ] && command -v update-desktop-database >/dev/null 2>&1; then update-desktop-database $(APPDIR) 2>/dev/null || true; fi

clean:
	rm -f $(ALL_TOOLS)
	rm -rf build

# --- faceshowx plugins ------------------------------------------------------
# build/plugins/<name>.so from faceshowx-plugins/plugins/<name>.c.  Add a plugin: drop
# its .c there and add the name to PLUGINS.
PLUGINS   := blur image
PLUGDIR   ?= $(or $(XDG_CONFIG_HOME),$(HOME)/.config)/betterx/plugins
PLUGFILES := $(PLUGINS:%=build/plugins/%.so)

plugins: $(PLUGFILES)

build/plugins/%.so: faceshowx-plugins/plugins/%.c faceshowx-plugins/plugins/fsx_seg.h faceshowx-plugins/include/fsx_plugin.h
	@mkdir -p build/plugins
	$(CC) $(CFLAGS) -fPIC -shared -Ifaceshowx-plugins/include -Ifaceshowx-plugins/plugins -o $@ $< -lm

# per user: do NOT run with sudo (it would go to root's ~/.config)
install-plugins: plugins
	@test "$$(id -u)" != 0 || { echo "run install-plugins as your own user, not root"; exit 1; }
	install -d "$(PLUGDIR)"
	install -m755 $(PLUGFILES) "$(PLUGDIR)/"
	@echo "installed to $(PLUGDIR) (each plugin gets its .conf on first run of faceshowx)"

# --- file manager integration -----------------------------------------------
# handrollerx writes the entries itself (Thunar uca.xml, Nautilus/Caja scripts, Nemo actions,
# Dolphin service menus, PCManFM actions) pointing at the handrollerx/renamex next to it.  Run it
# on the installed copy so the entries point at PREFIX/bin; FM=auto uses the file managers in PATH.
FM ?= auto
HX := $(or $(wildcard $(PREFIX)/bin/handrollerx),./handrollerx)

integrate: handrollerx
	@test "$$(id -u)" != 0 || { echo "run integrate as your own user, not root"; exit 1; }
	$(HX) --integrate $(FM)

unintegrate: handrollerx
	@test "$$(id -u)" != 0 || { echo "run unintegrate as your own user, not root"; exit 1; }
	$(HX) --unintegrate $(FM)
