# SPDX-License-Identifier: GPL-2.0-only

include ../../../scripts/Makefile.include
include ../../../scripts/utilities.mak

INSTALL ?= install
RM ?= rm -f
RMDIR ?= rmdir --ignore-fail-on-non-empty

ifeq ($(V),1)
  Q =
else
  Q = @
endif

prefix ?= /usr/local
mandir ?= $(prefix)/man
man2dir = $(mandir)/man2
man7dir = $(mandir)/man7

SYSCALL_RST = bpf-syscall.rst
MAN2_RST = $(SYSCALL_RST)

HELPERS_RST = bpf-helpers.rst
MAN7_RST = $(HELPERS_RST)

_DOC_MAN2 = $(patsubst %.rst,%.2,$(MAN2_RST))
DOC_MAN2 = $(addprefix $(OUTPUT),$(_DOC_MAN2))

_DOC_MAN7 = $(patsubst %.rst,%.7,$(MAN7_RST))
DOC_MAN7 = $(addprefix $(OUTPUT),$(_DOC_MAN7))

DOCTARGETS := helpers syscall

docs: $(DOCTARGETS)
syscall: man2
helpers: man7
man2: $(DOC_MAN2)
man7: $(DOC_MAN7)

RST2MAN_DEP := $(shell command -v rst2man 2>/dev/null)

# Configure make rules for the man page bpf-$1.$2.
# $1 - target for scripts/bpf_doc.py
# $2 - man page section to generate the troff file
define DOCS_RULES =
$(OUTPUT)bpf-$1.rst: ../../../../include/uapi/linux/bpf.h
	$$(QUIET_GEN)../../../../scripts/bpf_doc.py $1 \
		--filename $$< > $$@

$(OUTPUT)%.$2: $(OUTPUT)%.rst
ifndef RST2MAN_DEP
	$$(error "rst2man not found, but required to generate man pages")
endif
	$$(QUIET_GEN)rst2man --exit-status=1 $$< > $$@.tmp
	$$(QUIET_GEN)mv $$@.tmp $$@

docs-clean-$1:
	$$(call QUIET_CLEAN, eBPF_$1-manpage)
	$(Q)$(RM) $$(DOC_MAN$2) $(OUTPUT)bpf-$1.rst

docs-install-$1: docs
	$$(call QUIET_INSTALL, eBPF_$1-manpage)
	$(Q)$(INSTALL) -d -m 755 $(DESTDIR)$$(man$2dir)
	$(Q)$(INSTALL) -m 644 $$(DOC_MAN$2) $(DESTDIR)$$(man$2dir)

docs-uninstall-$1:
	$$(call QUIET_UNINST, eBPF_$1-manpage)
	$(Q)$(RM) $$(addprefix $(DESTDIR)$$(man$2dir)/,$$(_DOC_MAN$2))
	$(Q)$(RMDIR) $(DESTDIR)$$(man$2dir)

.PHONY: $1 docs-clean-$1 docs-install-$1 docs-uninstall-$1
endef

# Create the make targets to generate manual pages by name and section
$(eval $(call DOCS_RULES,helpers,7))
$(eval $(call DOCS_RULES,syscall,2))

docs-clean: $(foreach doctarget,$(DOCTARGETS), docs-clean-$(doctarget))
docs-install: $(foreach doctarget,$(DOCTARGETS), docs-install-$(doctarget))
docs-uninstall: $(foreach doctarget,$(DOCTARGETS), docs-uninstall-$(doctarget))

.PHONY: docs docs-clean docs-install docs-uninstall man2 man7