DATE := $(shell date +%F)
TIME := $(shell date +%H:%M)
LOGDIR := ../log/$(DATE)/$(TIME)

# bpf/ is at bpftests/bpf/, vm-credentials is written to bpftests/controller/
CREDENTIALS_FILE := ../controller/vm-credentials
VM_USER ?= $(shell sed -n 's/^VM_USER="\(.*\)"/\1/p' $(CREDENTIALS_FILE) 2>/dev/null)

VM_IP  := 192.168.100.10
VM_SSH := $(VM_USER)@$(VM_IP)

# Guard macro — insert at the top of any recipe that requires VM_USER
define check_vm_user
	@if [ -z "$(VM_USER)" ]; then \
		echo "Error: VM_USER is not set. Run build.sh first to generate $(CREDENTIALS_FILE)"; \
		exit 1; \
	fi
endef

all: bpf loader

bpf: vmlinux.h src/honeypot.bpf.c include/common.h
	clang -O2 -g -target bpf -D__TARGET_ARCH_x86 -c src/honeypot.bpf.c -o honeypot.bpf.o -I .
	/sbin/bpftool gen skeleton honeypot.bpf.o name honeypot_bpf > src/honeypot.skel.h

loader: src/loader.c src/honeypot.skel.h include/common.h
	clang -o loader src/loader.c -lbpf -lelf

vmlinux.h:
	/sbin/bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h

upload:
	$(call check_vm_user)
	sed "s|__USERNAME__|$(VM_USER)|g" include/data.h.template > include/data.h
	tar czf - Makefile src/*.c include/*.h | ssh $(VM_SSH) 'mkdir -p bpf && tar xzvf - -C bpf'

listen:
	mkdir -p $(LOGDIR)
	ln -sfn $(LOGDIR) ../log/current
	python ./listener.py --debug 1 --log $(LOGDIR)

go: upload
	$(call check_vm_user)
	ssh -tt $(VM_SSH) 'cd bpf && make go-on-pot VM_USER=$(VM_USER)'

go-on-pot: clean timesync load

clean:
	rm -f loader honeypot.bpf.o src/honeypot.skel.h

timesync:
	sudo apt install -y rdate
	sudo rdate -n pool.ntp.org

load: all
	sudo ./loader 192.168.100.1 1337 2>&1
	@status=$$?; \
	if [ $$status -eq 0 ]; then \
		echo "Loader exited cleanly."; \
		exit 0; \
	else \
		echo "Loader failed with code $$status"; \
		exit 1; \
	fi
