# SPDX-License-Identifier: GPL-3.0-or-later
# pomelo-packets — 封包分析器（pcap／pcapng 分析、擷取、RTP 與 VoIP 品質）
PREFIX ?= /usr/local
CFLAGS ?= -Os -pipe -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation -Wno-missing-field-initializers -Wno-misleading-indentation -Wno-format-security
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)

CORE = pcapio.c dissect.c filter.c analyze.c priv.c media.c bpf.c capture.c cli.c
GUI  = gui.c
HDR  = pk.h cli.h capture.h
DBG  = -O1 -g -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation -Wno-missing-field-initializers -Wno-misleading-indentation -Wno-format-security -DPK_NOGUI

all: pomelo-packets pomelo-packets-helper pomelo-packets.png

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

# 特權輔助程式：只依賴 bpf.c，不連 libpomelo、cairo
pomelo-packets-helper: helper.c bpf.c pk.h
	$(CC) $(CFLAGS) -DPK_NOGUI -o $@ helper.c bpf.c $(LDFLAGS)

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

# 無圖形介面的命令列版（測試、伺服器、容器）
test/pk-cli: main-core.c $(CORE) $(HDR)
	$(CC) $(DBG) -o $@ main-core.c $(CORE) -lm -lpthread -ldl

test/test-packets: test/test-packets.c $(CORE) $(HDR)
	$(CC) $(DBG) -I. -o $@ test/test-packets.c $(CORE) -lm -lpthread -ldl

test: test/test-packets test/pk-cli pomelo-packets-helper
	python3 test/lab/synth.py test/fixtures
	TESTTMP=$${TESTTMP:-/tmp} test/test-packets test/fixtures
	python3 test/check-rtp.py test/pk-cli test/fixtures

install: all
	install -Dm755 pomelo-packets $(DESTDIR)$(PREFIX)/bin/pomelo-packets
	install -Dm644 pomelo-packets.desktop $(DESTDIR)$(PREFIX)/share/applications/pomelo-packets.desktop
	install -Dm644 pomelo-packets.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps/pomelo-packets.png
	# 特權輔助程式：不是 setuid；預設由 pkexec 取得權限（polkit 政策），管理員也可以改用 setcap cap_net_raw+ep
	install -Dm755 pomelo-packets-helper $(DESTDIR)$(PREFIX)/libexec/pomelo/pomelo-packets-helper
	install -Dm644 tw.fedora.pomelo.packets.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/tw.fedora.pomelo.packets.policy
	sed -i 's|/usr/libexec/pomelo|$(PREFIX)/libexec/pomelo|' $(DESTDIR)$(PREFIX)/share/polkit-1/actions/tw.fedora.pomelo.packets.policy

clean:
	$(RM) pomelo-packets pomelo-packets-helper pomelo-packets.png *.o test/test-packets test/pk-cli

.PHONY: all clean test install
