# tinyrd — the rawnix initramfs
# https://rawnix.org
#
# tinyrd links a static libcryptsetup and libdevmapper.  The port builds
# both privately, never installing them system-wide, and passes their
# prefix:
#
#     make STATIC_PREFIX=/path/to/private/prefix image
#
# The link line comes from pkg-config, which needs PKG_CONFIG_PATH to
# point into that prefix; the port exports it already, so passing LIBS
# in is equally good and is what it does:
#
#     make STATIC_PREFIX=$_p LIBS="$(pkg-config --static --libs libcryptsetup)"
#
# "image" writes tinyrd.img by running the binary it just built; that
# image is what gets packaged.  "all" stops at the binary.

CC         ?= cc
PKG_CONFIG ?= pkg-config

# _GNU_SOURCE is defined by tinyrd.c itself; defining it here too only
# earns a -Wmacro-redefined warning.
CFLAGS  += -std=c99 -Wall -Wextra -Os

STATIC_PREFIX ?= /usr

CPPFLAGS += -I$(STATIC_PREFIX)/include
LDFLAGS  += -L$(STATIC_PREFIX)/lib

# ?= so the port can hand the line in ready-made.  The default is a
# recursive variable on purpose: it runs pkg-config only if it is
# actually used, and only after STATIC_PREFIX has its final value.
LIBS ?= $(shell PKG_CONFIG_PATH=$(STATIC_PREFIX)/lib/pkgconfig \
                $(PKG_CONFIG) --static --libs libcryptsetup)

PREFIX  ?= /usr
MANDIR   = $(PREFIX)/share/man
BOOTDIR  = /boot

all: tinyrd

# static is mandatory: /init runs before anything holding a shared
# library is mounted, and tinyrd refuses to build an image from a
# dynamic binary.
tinyrd: tinyrd.c
	@test -n "$(strip $(LIBS))" || { \
		echo "tinyrd: no libcryptsetup: set STATIC_PREFIX, or pass LIBS=" >&2; \
		exit 1; }
	$(CC) $(CFLAGS) $(CPPFLAGS) -static -o $@ $< $(LDFLAGS) $(LIBS)

image: tinyrd
	./tinyrd -o tinyrd.img

install: image
	install -Dm644 tinyrd.img $(DESTDIR)$(BOOTDIR)/tinyrd.img
	install -Dm644 tinyrd.8 $(DESTDIR)$(MANDIR)/man8/tinyrd.8

uninstall:
	rm -f $(DESTDIR)$(BOOTDIR)/tinyrd.img
	rm -f $(DESTDIR)$(MANDIR)/man8/tinyrd.8

lint:
	mandoc -Tlint tinyrd.8

clean:
	rm -f tinyrd tinyrd.img

.PHONY: all image install uninstall lint clean
