CC := gcc
CARGO := rustup run nightly cargo

TARGET := x86_64-unknown-linux-musl
PROFILE := size-optimized
FEATURES := protocol_udp

THIS_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
REPO_ROOT := $(THIS_DIR)/..
RUST_TARGET_DIR := $(REPO_ROOT)/target/$(TARGET)/$(PROFILE)
export SERVICEPOINT_HEADER_OUT := $(REPO_ROOT)/include

RUSTFLAGS := -Zlocation-detail=none \
	-Zfmt-debug=none \
	-C linker=musl-gcc \
	-C link-arg=-s \
	-C link-arg=--gc-sections \
	-C link-arg=-z,norelro \
	-C link-arg=--hash-style=gnu \
	--crate-type=staticlib \
	-C panic=abort

CARGOFLAGS := --manifest-path=$(REPO_ROOT)/Cargo.toml \
	--profile=$(PROFILE) \
	--no-default-features \
	--features=$(FEATURES) \
	--target=$(TARGET) \
	-Zbuild-std="core,std,alloc,proc_macro,panic_abort" \
	-Zbuild-std-features="panic_immediate_abort" \

CCFLAGS := -static -Os \
	-ffunction-sections -fdata-sections \
	-fwrapv -fomit-frame-pointer -fno-stack-protector\
	-fwhole-program \
	-nodefaultlibs -lservicepoint_binding_c -lc \
	-Wl,--gc-sections \
	-fno-unroll-loops \
	-fno-unwind-tables -fno-asynchronous-unwind-tables \
	-fmerge-all-constants \
	-Wl,-z,norelro \
	-Wl,--hash-style=gnu \
	-fvisibility=hidden \
	-Bsymbolic \
	-Wl,--exclude-libs,ALL \
	-fno-ident \
	-Wall
	#-fuse-ld=gold \
	-fno-exceptions
	#-Wl,--icf=all \

STRIPFLAGS := -s --strip-unneeded -R .comment -R .gnu.version -R .comment -R .note -R .note.gnu.build-id -R .note.ABI-tag

_c_src := $(wildcard *.c)
_programs := $(basename $(_c_src))
_bins := $(addprefix out/, $(_programs))
_unstripped_bins := $(addsuffix _unstripped, $(_bins))
_run_programs := $(addprefix run_, $(_programs))
_rs_src := $(wildcard ../src/**.rs) ../Cargo.lock ../Cargo.toml ../cbindgen.toml

all: $(_bins)

clean:
	rm -r out || true
	rm include/servicepoint.h || true
	cargo clean

PHONY: all clean sizes $(_run_programs)

$(_unstripped_bins): out/%_unstripped: %.c $(SERVICEPOINT_HEADER_OUT)/servicepoint.h $(RUST_TARGET_DIR)/libservicepoint_binding_c.a
	mkdir -p out || true
	${CC} $^ \
		-I $(SERVICEPOINT_HEADER_OUT) \
		-L $(RUST_TARGET_DIR)\
		$(CCFLAGS) \
		-o $@

$(_bins): out/%: out/%_unstripped
	strip $(STRIPFLAGS) $^ -o $@

$(SERVICEPOINT_HEADER_OUT)/servicepoint.h $(RUST_TARGET_DIR)/libservicepoint_binding_c.a: $(_rs_src)
	mkdir -p include || true
	# generate servicepoint header and binary to link against
	${CARGO} rustc $(CARGOFLAGS) -- $(RUSTFLAGS)

$(_run_programs): run_%: out/% FORCE
	./$<

sizes: $(_bins)
	ls -lB out

#analyze-size: out/example_unstripped
#	nm --print-size --size-sort --reverse-sort --radix=d --demangle out/example_unstripped \
#		| awk '{size=$$2+0; print size "\t" $$4}' \
#		| less

FORCE: ;