# Makefile - Filature
#
# Copyright (C) 2026 SliTaz GNU/Linux - BSD License, see LICENSE
#
# The config path is compiled in: the binary is setgid and must not take
# it from the environment. Tests build with CONF pointing elsewhere.

PREFIX     ?= /usr
SYSCONFDIR ?= /etc
CONF       ?= $(SYSCONFDIR)/filature/filature.conf

DESTDIR    ?=
SHAREDIR    = $(PREFIX)/share/filature

# -Werror while developing; a package build may drop it (WERROR=)
CC      ?= gcc
CFLAGS  ?= -O2
WERROR  ?= -Werror
# The binary is setgid: a stray overflow must abort, not run
HARDEN  ?= -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE
HARDEN_LD ?= -pie -Wl,-z,relro,-z,now
CFLAGS  += -std=c99 -D_GNU_SOURCE -Wall -Wextra $(WERROR) $(HARDEN) \
           -DFIL_CONF='"$(CONF)"'
LDFLAGS += $(HARDEN_LD)
LDLIBS   = -lsqlite3

SRCS = src/main.c src/util.c src/config.c src/db.c src/html.c \
       src/cgi.c src/cli.c src/sha256.c src/rand.c src/auth.c \
       src/hooks.c src/mod_threads.c src/mod_mail.c \
       src/mod_bugs.c src/mod_hg.c src/mod_news.c \
       src/mod_help.c src/mod_check.c
OBJS = $(SRCS:.c=.o) src/schema.o

all: fil

fil: $(OBJS)
	$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS)

$(OBJS): src/fil.h Makefile

src/schema.c: src/sql2c.sh $(wildcard sql/*.sql)
	sh src/sql2c.sh $(sort $(wildcard sql/*.sql)) > $@

# The server. fil goes in 755: the package post_install (or
# deploy/install.sh) makes it setgid filature, once the group exists.
install: fil
	install -Dm755 fil $(DESTDIR)$(PREFIX)/bin/fil
	install -Dm755 hooks/hg-changegroup $(DESTDIR)$(SHAREDIR)/hg-changegroup
	install -Dm644 hooks/message.new.sample $(DESTDIR)$(SHAREDIR)/message.new.sample
	for f in style.css logo.png favicon.ico; do \
		install -Dm644 web/$$f $(DESTDIR)$(SHAREDIR)/web/$$f; \
	done
	install -Dm644 deploy/lighttpd.conf $(DESTDIR)$(SHAREDIR)/lighttpd.conf
	install -Dm644 doc/filature.conf $(DESTDIR)$(SYSCONFDIR)/filature/filature.conf
	install -d -m 755 $(DESTDIR)$(SYSCONFDIR)/filature/hooks
	install -Dm644 doc/DECISIONS.md $(DESTDIR)$(PREFIX)/share/doc/filature/DECISIONS.md
	install -Dm644 doc/mail-bridge.md $(DESTDIR)$(PREFIX)/share/doc/filature/mail-bridge.md

# Needs root, inside the SliTaz build chroot: see doc/AGENTS.md
test:
	sh tests/run.sh

clean:
	rm -f fil src/*.o src/schema.c

.PHONY: all install test clean
