# hellgate v3 + hellmon - THE ROUTER FROM HELL, integrated build
#
# Build deps (Gentoo):
#   emerge --ask llvm-core/clang dev-libs/libbpf dev-util/bpftool
# Runtime deps: libbpf.so for hellgate; hellmon needs NOTHING beyond
# glibc (raw bpf(2) syscalls + one unix socket).
#
# Targets:
#   make            build both binaries
#   make hellgate   daemon+CLI (embeds the XDP program via skeleton)
#   make hellmon    monitor (hellgate_page.c is #include'd, not linked)
#   make install    install binaries + initd + conf

CLANG   ?= clang
BPFTOOL ?= bpftool
CC      ?= gcc
BPF_CFLAGS := -O2 -g -Wall -target bpf -D__TARGET_ARCH_x86
CFLAGS     := -O2 -Wall -Wextra

all: hellgate hellmon

# ---- the gate ------------------------------------------------------
hellgate.bpf.o: hellgate.bpf.c
	$(CLANG) $(BPF_CFLAGS) -c $< -o $@

hellgate.skel.h: hellgate.bpf.o
	$(BPFTOOL) gen skeleton $< > $@

hellgate: hellgated.c hellgate.skel.h
	$(CC) $(CFLAGS) -o $@ hellgated.c -lbpf -lelf -lz

# ---- the monitor ---------------------------------------------------
# hellgate_page.c is a dependency because hellmon.c #include's it:
# touch either file and hellmon rebuilds.
hellmon: hellmon.c hellgate_page.c
	$(CC) $(CFLAGS) -o $@ hellmon.c

clean:
	rm -f hellgate hellmon hellgate.bpf.o hellgate.skel.h

install: hellgate hellmon
	install -m 0755 hellgate       /usr/local/sbin/hellgate
	install -m 0755 hellmon        /usr/local/sbin/hellmon
	install -m 0755 hellgate.initd /etc/init.d/hellgate
	@[ -e /etc/hellgate.conf ] || \
	    printf 'WAN_IF="enp16s0f0np0"\n' > /etc/hellgate.conf
	@echo "installed: hellgate + hellmon."
	@echo "next: rc-update add hellgate default && rc-service hellgate start && sudo hellmon"

inspect:
	$(BPFTOOL) prog show name hellgate
	$(BPFTOOL) map show | grep hellgate || true

.PHONY: all clean install inspect

# delete half-written targets when a recipe fails (e.g. bpftool dying
# after the > redirect already created an empty skel.h)
.DELETE_ON_ERROR:
