# Builds the sample target. If the host has no compiler - common on a locked-down
# RHEL 9.6 server, and not worth fixing just to run this kit - it installs the
# prebuilt copies from ../prebuilt instead. Those were compiled against glibc
# 2.34 (RHEL 9's baseline), so they run on any RHEL 9 without a toolchain.
#
# We deliberately do NOT ship gcc: glibc-devel requires an exact glibc NEVRA, so
# installing it would force an upgrade of the host's C library.

# make defines CC=cc as a built-in, so `CC ?= ...` never fires. Only override it
# when it is still that built-in default - an explicit CC= from the environment
# or the command line must win.
ifeq ($(origin CC),default)
CC := $(shell command -v gcc 2>/dev/null || command -v cc 2>/dev/null)
endif
CFLAGS   ?= -O1 -g -Wall -Wextra -fno-omit-frame-pointer
PREBUILT := $(CURDIR)/../prebuilt

TARGETS := sample_app sample_helper libsampleplugin.so sample_app.stripped

all: $(TARGETS)

ifeq ($(strip $(CC)),)

# ---- no compiler: install the prebuilt binaries -----------------------------
$(TARGETS): %: $(PREBUILT)/%
	@echo "  no C compiler on this host - installing prebuilt $@"
	@cp -f $< $@ && chmod +x $@

else

# ---- normal build ------------------------------------------------------------
sample_app: sample_app.c
	$(CC) $(CFLAGS) -o $@ $< -ldl

sample_helper: helper.c
	$(CC) $(CFLAGS) -o $@ $<

libsampleplugin.so: plugin.c
	$(CC) $(CFLAGS) -shared -fPIC -o $@ $<

# a stripped copy, to practise on a binary with no symbols
sample_app.stripped: sample_app
	cp -f $< $@ && { command -v strip >/dev/null && strip -s $@ || \
	  echo "  (binutils absent - $@ is an unstripped copy)"; }

endif

check:
	@echo "CC = $(if $(CC),$(CC),none - will use $(PREBUILT))"

clean:
	rm -f sample_app sample_helper libsampleplugin.so sample_app.stripped

.PHONY: all clean check
