# SPDX-License-Identifier: GPL-3.0-or-later
# pomelo-gpu — 顯卡監視（NVIDIA 用 NVML 或 nvidia-smi、AMD／Intel／虛擬顯示卡用 sysfs；處理程序、容器、AI 模型）
PREFIX ?= /usr/local
CFLAGS ?= -Os -pipe -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation -Wno-format-nonliteral -Wno-unused-function
override CFLAGS += -fstack-protector-strong -fstack-clash-protection -D_FORTIFY_SOURCE=3 -fPIE -pie
override LDFLAGS += -Wl,-z,relro,-z,now
POMELO_CFLAGS ?= $(shell pkg-config --cflags pomelo)
POMELO_LIBS   ?= $(shell pkg-config --libs pomelo)
CAIRO_CFLAGS ?= $(shell pkg-config --cflags cairo)
CAIRO_LIBS   ?= $(shell pkg-config --libs cairo)

# 核心：不需要顯示器與 libpomelo（命令列、單元測試、管理員輔助程式直接編）。libnvidia-ml 用 dlopen，不連結任何 NVIDIA 東西。
CORE = util.c nvml.c smi.c sysfs.c procs.c models.c alerts.c guide.c collect.c cli.c
HDR  = gpu.h

all: pomelo-gpu pomelo-gpu-admin pomelo-gpu.png

pomelo-gpu: $(CORE) gui.c main.c $(HDR)
	$(CC) $(CFLAGS) $(POMELO_CFLAGS) $(CAIRO_CFLAGS) -o $@ $(CORE) gui.c main.c $(POMELO_LIBS) $(CAIRO_LIBS) -ldl -lpthread -lm $(LDFLAGS)

# 唯讀的管理員輔助程式：只輸出 GPU 編號、PID、名稱、顯示記憶體
pomelo-gpu-admin: admin.c $(CORE) $(HDR)
	$(CC) $(CFLAGS) -o $@ admin.c $(CORE) -ldl -lpthread -lm $(LDFLAGS)

pomelo-gpu.png: pomelo-gpu
	LD_LIBRARY_PATH="$(LD_LIBRARY_PATH)" ./pomelo-gpu --icon $@

# 測試用的假 NVML（共享函式庫）與單元測試
test/fake/libnvidia-ml.so.1: test/fake/fake-nvml.c
	$(CC) -shared -fPIC -O1 -o $@ $< -lm

test/test-gpu: test/test-gpu.c $(CORE) $(HDR)
	$(CC) -O1 -g -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation -Wno-format-nonliteral -I. -o $@ test/test-gpu.c $(CORE) -ldl -lpthread -lm

test: test/test-gpu test/fake/libnvidia-ml.so.1
	sh test/run-unit.sh
	@if command -v python3 >/dev/null 2>&1; then sh test/e2e.sh; else echo "略過端對端測試（需要 python3）"; fi

install: all
	install -Dm755 pomelo-gpu $(DESTDIR)$(PREFIX)/bin/pomelo-gpu
	install -Dm644 pomelo-gpu.desktop $(DESTDIR)$(PREFIX)/share/applications/pomelo-gpu.desktop
	install -Dm644 pomelo-gpu.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps/pomelo-gpu.png
	# 唯讀輔助程式：不是 setuid；由 pkexec（polkit 政策）取得權限
	install -Dm755 pomelo-gpu-admin $(DESTDIR)$(PREFIX)/libexec/pomelo/pomelo-gpu-admin
	install -Dm644 tw.fedora.pomelo.gpu.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/tw.fedora.pomelo.gpu.policy
	sed -i 's|/usr/libexec/pomelo|$(PREFIX)/libexec/pomelo|' $(DESTDIR)$(PREFIX)/share/polkit-1/actions/tw.fedora.pomelo.gpu.policy
	# 定時檢查的 systemd 使用者定時器（預設關閉：不放進 timers.target.wants，要自己 enable）
	for u in service timer; do install -Dm644 systemd/pomelo-gpu-check.$$u $(DESTDIR)$(PREFIX)/lib/systemd/user/pomelo-gpu-check.$$u; done
	sed -i 's|/usr/bin/pomelo-gpu|$(PREFIX)/bin/pomelo-gpu|' $(DESTDIR)$(PREFIX)/lib/systemd/user/pomelo-gpu-check.service

clean:
	rm -f pomelo-gpu pomelo-gpu-admin pomelo-gpu.png *.o test/test-gpu test/gp-cli test/fake/libnvidia-ml.so.1

.PHONY: all clean test install
