# SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
# Copyright (c) 2024 Brett Sheffield <bacs@librecast.net>

PREFIX ?= @prefix@
export PREFIX
PROGRAM := @PACKAGE_NAME@
VERSION := @PACKAGE_VERSION@
COVERITY_DIR := cov-int
COVERITY_TGZ := $(PROGRAM)-coverity-$(VERSION).tgz
COVERITY_PATH=$(PATH):../../coverity/bin/
OSNAME := $(shell uname -s)
export OSNAME

export SOURCEDIR=$(shell pwd)

ifeq ($(origin CC),default)
CC = @CC@
endif
export CC

CFLAGS ?= @CFLAGS@
ifdef DEBUG
CFLAGS += -Og -g -Wall -Wextra -pedantic
endif
export CFLAGS

CPPFLAGS += @CPPFLAGS@
export CPPFLAGS

LDFLAGS ?= @LDFLAGS@
export LDFLAGS

all: src

install: all
	$(MAKE) -C src $@
	$(MAKE) -C man $@

uninstall:
	$(MAKE) -C src $@
	$(MAKE) -C man $@

.PHONY: clean realclean src test testloop sparse doc netcheck net-teardown testshell update newtest

src:
	$(MAKE) -C $@

doc:
	$(MAKE) -C doc $@

fixme:
	grep -n FIXME src/*.{c,h} test/*.{c,h}

todo:
	grep -n TODO src/*.{c,h} test/*.{c,h}

clean:
	$(MAKE) -C src $@
	$(MAKE) -C test $@
	$(MAKE) -C man $@

realclean: clean
	$(MAKE) -C src $@
	$(MAKE) -C test $@
	$(MAKE) -C man $@
	$(RM) -r ./$(COVERITY_DIR)
	$(RM) $(COVERITY_TGZ)
	$(RM) Makefile
	$(RM) config.{log,status}
	$(RM) include/librecast/crypto.h


sparse: clean
	CC=cgcc $(MAKE) src

clang: clean
	CC=clang $(MAKE) src

clangtest: clean
	CC=clang $(MAKE) test

gcc: clean all

netcheck:
	$(MAKE) -C test $@

test memcheck: src netcheck
	$(MAKE) -C test $@/all

newtest:
	$(MAKE) -C test $@

LOOPBANNER ?= echo

testloop:
	num_ok=0; \
	while $(MAKE) $(subst testloop,test,$@); do \
	num_ok=$$(( $$num_ok + 1 )); \
	make -C test logclean; \
	echo; \
	echo; \
	$(LOOPBANNER) "OK $$num_ok"; \
	echo; \
	sleep 1; \
	done; \
	$(LOOPBANNER) "OK $$num_ok"

testloop/%:
	num_ok=0; \
	while $(MAKE) $(subst testloop,test,$@); do \
	num_ok=$$(( $$num_ok + 1 )); \
	make -C test logclean; \
	echo; \
	echo; \
	$(LOOPBANNER) "OK $$num_ok"; \
	echo; \
	done; \
	$(LOOPBANNER) "OK $$num_ok"

test/% memcheck/%: .FORCE src
	$(MAKE) -C test $@

.FORCE: # always recompile

coverity: clean
	PATH=$(COVERITY_PATH) cov-build --dir cov-int $(MAKE) src
	tar czvf $(COVERITY_TGZ) $(COVERITY_DIR)

net-setup:
	ip link add veth0 type veth peer name veth1
	ip netns add vnet0
	ip netns add vnet1
	ip link set veth0 netns vnet0
	ip link set veth1 netns vnet1
	ip -n vnet0 link set veth0 up
	ip -n vnet1 link set veth1 up
	ip netns show
	touch net-setup

net-teardown:
	ip -n vnet0 link set veth0 down
	ip -n vnet1 link set veth1 down
	ip -n vnet1 link set veth1 netns vnet0
	ip -n vnet0 link del veth0 type veth peer name veth1
	ip netns del vnet0
	ip netns del vnet1
	ip netns show
	rm -f net-setup

testshell:
	@echo "sudo ip netns exec vnet0 sudo -u `id -un` /bin/bash"
