# SPDX-License-Identifier: GPL-3.0-or-later
# pomelo-screensaver — Pomelo 螢幕保護程式
PREFIX ?= /usr/local
CFLAGS ?= -Os -pipe -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation
# 編譯防護（Ubuntu 的 gcc 預設就有，Fedora／Rocky 要自己加）：堆疊保護、PIE、FORTIFY、完整 RELRO
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)
DBUS_CFLAGS ?= $(shell pkg-config --cflags dbus-1)
DBUS_LIBS   ?= $(shell pkg-config --libs dbus-1)

# 小柚的造型與圖資直接連結 ../pomelo-assistant（不複製）；農曆用 ../pomelo-calendar 的 lunar.c／cal.c
ASST = ../pomelo-assistant
MASCOT = $(ASST)/mascot-data.c $(ASST)/mascot-girl-data.c $(ASST)/mascot-woman-data.c $(ASST)/mascot-woman-sit-data.c \
         $(ASST)/mascot-woman-sleep-data.c $(ASST)/mascot-girl-sleep-data.c $(ASST)/mascot-walk-girl-data.c \
         $(ASST)/mascot-sitdown-girl-data.c $(ASST)/mascot-sleepdown-girl-data.c
KINDS = k-clock.c k-photos.c k-pet.c k-flow.c k-stars.c k-bubbles.c k-text.c
SRC = main.c backend.c ui.c draw.c media.c image.c conf.c util.c $(KINDS)
ALL_CFLAGS = $(CFLAGS) $(POMELO_CFLAGS) $(DBUS_CFLAGS) -I.

all: pomelo-screensaver pomelo-screensaver.png

robot.o: $(ASST)/robot.c $(ASST)/robot.h
	$(CC) $(CFLAGS) $(POMELO_CFLAGS) -O2 -c -o $@ $(ASST)/robot.c
lunar.o: ../pomelo-calendar/lunar.c ../pomelo-calendar/cal.h
	$(CC) $(CFLAGS) -c -o $@ ../pomelo-calendar/lunar.c
cal.o: ../pomelo-calendar/cal.c ../pomelo-calendar/cal.h
	$(CC) $(CFLAGS) -c -o $@ ../pomelo-calendar/cal.c

pomelo-screensaver: $(SRC) saver.h saver-idle.h backend.h robot.o lunar.o cal.o $(MASCOT)
	$(CC) $(ALL_CFLAGS) -o $@ $(SRC) robot.o lunar.o cal.o $(MASCOT) $(POMELO_LIBS) $(DBUS_LIBS) -lXext -lXrandr -lpthread -ldl -lm $(LDFLAGS)

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

# 單元測試（不需要顯示器）：設定驗證與衝突提示、時鐘漂移、幻燈片排程與洗牌、圖片載入的錯誤處理
test/test-saver: test/test-saver.c conf.c util.c image.c saver.h saver-idle.h
	$(CC) -g -O1 -Wall -Wextra -Wno-unused-parameter -Wno-format-truncation $(POMELO_CFLAGS) -I. -o $@ test/test-saver.c conf.c util.c image.c $(POMELO_LIBS) -ldl -lm

test: test/test-saver
	@[ -d test/fixtures ] || python3 test/gen-fixtures.py test/fixtures
	@mkdir -p test/tmp
	TESTTMP="$(CURDIR)/test/tmp" LD_LIBRARY_PATH="$(LD_LIBRARY_PATH)" test/test-saver test/fixtures

install: all
	install -Dm755 pomelo-screensaver $(DESTDIR)$(PREFIX)/bin/pomelo-screensaver
	install -Dm644 pomelo-screensaver.desktop $(DESTDIR)$(PREFIX)/share/applications/pomelo-screensaver.desktop
	install -Dm644 pomelo-screensaver.png $(DESTDIR)$(PREFIX)/share/icons/hicolor/256x256/apps/pomelo-screensaver.png

clean:
	rm -f pomelo-screensaver pomelo-screensaver.png *.o test/test-saver

.PHONY: all install clean test
