# SPDX-License-Identifier: GPL-3.0-or-later
# pomelo-firewall — Pomelo 防火牆管理員（iptables 的圖形管理介面）
PREFIX ?= /usr/local
CFLAGS ?= -Os -pipe -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation
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)

# 核心：不需要顯示器與 libpomelo（helper、命令列、單元測試共用）
CORE = util.c ipt.c edit.c advise.c protect.c watch.c precheck.c template.c backend.c ops.c

GUI  = gui.c
HDR  = fw.h
DBG  = -g -O1 -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation

all: pomelo-firewall pomelo-firewall-helper pomelo-firewall.png

pomelo-firewall: $(CORE) client.c $(GUI) cli.c main.c $(HDR)
	$(CC) $(CFLAGS) $(POMELO_CFLAGS) -DFW_USE_PM_TR -DHELPER_PATH='"$(PREFIX)/libexec/pomelo/pomelo-firewall-helper"' -D'_(s)=pm_tr(s)' -o $@ $(CORE) client.c $(GUI) cli.c main.c $(POMELO_LIBS) -lm -lpthread $(LDFLAGS)

# 特權輔助程式：不連 libpomelo、cairo；只接受白名單操作與已驗證的結構化參數，不接受任意 iptables 指令
pomelo-firewall-helper: helper.c $(CORE) $(HDR)
	$(CC) $(CFLAGS) -o $@ helper.c $(CORE) $(LDFLAGS)

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

test/test-fw: test/test-fw.c $(CORE) client.c $(HDR)
	$(CC) $(DBG) -o $@ test/test-fw.c $(CORE)

test: test/test-fw
	test/test-fw test/fixtures

install: all
	install -Dm755 pomelo-firewall $(DESTDIR)$(PREFIX)/bin/pomelo-firewall
	install -Dm644 pomelo-firewall.desktop $(DESTDIR)$(PREFIX)/share/applications/pomelo-firewall.desktop
	install -Dm644 pomelo-firewall.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps/pomelo-firewall.png
	# 特權輔助程式：不是 setuid；由 pkexec 取得權限（polkit 政策）
	install -Dm755 pomelo-firewall-helper $(DESTDIR)$(PREFIX)/libexec/pomelo/pomelo-firewall-helper
	install -Dm644 tw.fedora.pomelo.firewall.policy $(DESTDIR)$(PREFIX)/share/polkit-1/actions/tw.fedora.pomelo.firewall.policy
	sed -i 's|/usr/libexec/pomelo|$(PREFIX)/libexec/pomelo|' $(DESTDIR)$(PREFIX)/share/polkit-1/actions/tw.fedora.pomelo.firewall.policy
	# 開機還原（選用：系統沒有任何持久化機制、使用者同意時才 enable）
	install -Dm644 systemd/pomelo-firewall.service $(DESTDIR)$(PREFIX)/lib/systemd/system/pomelo-firewall.service
	sed -i 's|/usr/libexec/pomelo|$(PREFIX)/libexec/pomelo|' $(DESTDIR)$(PREFIX)/lib/systemd/system/pomelo-firewall.service
	# 選用：日誌式自動封鎖（預設關閉）
	install -Dm644 systemd/pomelo-firewall-watch.service $(DESTDIR)$(PREFIX)/lib/systemd/system/pomelo-firewall-watch.service
	sed -i 's|/usr/libexec/pomelo|$(PREFIX)/libexec/pomelo|' $(DESTDIR)$(PREFIX)/lib/systemd/system/pomelo-firewall-watch.service

clean:
	rm -f pomelo-firewall pomelo-firewall-helper pomelo-firewall.png *.o test/test-fw

.PHONY: all clean test install
