CC := gcc
CARGO := rustup run nightly cargo

THIS_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
REPO_ROOT := $(THIS_DIR)/..
RUST_TARGET_DIR := $(REPO_ROOT)/target/x86_64-unknown-linux-musl/size-optimized

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=size-optimized \
	--no-default-features \
	--target=x86_64-unknown-linux-musl \
	-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
	#-fuse-ld=gold \
	-fno-exceptions
	#-Wl,--icf=all \

export SERVICEPOINT_HEADER_OUT := $(REPO_ROOT)/include

build: out/example

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

run: out/example
	out/example

PHONY: build clean dependencies run

out/example_unstripped: dependencies main.c
	mkdir -p out || true
	${CC} main.c \
		-I $(SERVICEPOINT_HEADER_OUT) \
		-L $(RUST_TARGET_DIR)\
		$(CCFLAGS) \
		-o out/example_unstripped
out/example: out/example_unstripped
	strip -s --strip-unneeded \
		-R .comment -R .gnu.version -R .comment -R .note -R .note.gnu.build-id -R .note.ABI-tag \
		out/example_unstripped \
		-o out/example

dependencies: FORCE
	mkdir -p include || true
	# generate servicepoint header and binary to link against
	${CARGO} rustc $(CARGOFLAGS) -- $(RUSTFLAGS)

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: ;