# Copyright (c) 2023–2024 Emma Tebibyte <emma@tebibyte.media>
# Copyright (c) 2023 DTB <trinity@trinity.moe>
# Copyright (c) 2023 Sasha Koshka <sashakoshka@tebibyte.media>
# SPDX-License-Identifier: FSFAP
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice and this
# notice are preserved.  This file is offered as-is, without any warranty.

.POSIX:
.PRAGMA: posix_202x # future POSIX standard support à la pdpmake(1)

.PHONY: all
.PHONY: clean
.PHONY: install
.PHONY: test

PREFIX=/usr/local

CC=cc
RUSTC=rustc

# to build, first run ./configure
include *.mk

all: false fop intcmp scrut str strcmp true

build:
	# keep build/include until bindgen(1) has stdin support
	# https://github.com/rust-lang/rust-bindgen/issues/2703
	mkdir -p build/bin build/include build/lib build/o build/test

clean:
	rm -rf build/ dist/

dist: all
	mkdir -p \
	dist/bin \
	dist/man/man1 \
	# dist/$(PREFIX)/lib \
	# dist/$(PREFIX)/man/man3
	cp build/bin/* dist/bin/
	# cp build/lib/* dist/$(PREFIX)/lib/
	cp docs/*.1 dist/man/man1/
	# cp docs/*.3 dist/$(PREFIX)/man/man3/

install: dist
	mkdir -p $(PREFIX)
	cp -r dist/* $(PREFIX)/

test: build
	tests/cc-compat.sh
	tests/posix-compat.sh
	$(RUSTC) --test src/getopt-rs/lib.rs -o build/test/getopt

sysexits: build
	# bandage solution until bindgen(1) gets stdin support
	printf '#define EXIT_FAILURE 1\n' | cat - include/sysexits.h \
		> build/include/sysexits.h 
	bindgen --default-macro-constant-type signed --use-core --formatter=none \
		"$$(printf '#include <sysexits.h>\n' \
			| cpp -M -idirafter "build/include" - \
			| sed 's/ /\n/g' | grep sysexits.h)" \
		| $(RUSTC) $(RUSTCFLAGS) --crate-type lib -o build/o/libsysexits.rlib -

libgetopt: src/getopt-rs/lib.rs
	$(RUSTC) $(RUSTCFLAGS) --crate-type=lib --crate-name=getopt \
		-o build/o/libgetopt.rlib src/getopt-rs/lib.rs

false: src/false.rs build
	$(RUSTC) $(RUSTFLAGS) -o build/bin/false src/false.rs

fop: src/fop.rs build libgetopt sysexits
	$(RUSTC) $(RUSTFLAGS) --extern getopt=build/o/libgetopt.rlib \
		-o build/bin/fop src/fop.rs

intcmp: src/intcmp.c build
	$(CC) $(CFLAGS) -o build/bin/intcmp src/intcmp.c

scrut: src/scrut.c build
	$(CC) $(CFLAGS) -o build/bin/scrut src/scrut.c

str: src/str.c build
	$(CC) $(CFLAGS) -o build/bin/str src/str.c

strcmp: src/strcmp.c build
	$(CC) $(CFLAGS) -o build/bin/strcmp src/strcmp.c

true: src/true.rs build
	$(RUSTC) $(RUSTFLAGS) -o build/bin/true src/true.rs