# SPDX-License-Identifier: BSD-2-Clause
#
# Automatically find DLL dependencies, transitively.
#
# Copyright © 2021 David Woodhouse <dwmw2@infradead.org>
#
# Each .d file is auto-generated on demand when make tries to include
# it. It is generated by a pattern rule from the corresponding DLL
# binary, either in the local .libs directory or in the MinGw sys-root
# which ought to be $(bindir).
#
# The Makefile snippet in each generated file adds the full DLL pathname
# to $(DLLS), adds the .d file and the DLL itself to the dependencies of
# file-list.txt, and then includes more .d files for each other DLL that
# this DLL links to.
#
# Because we use -include, we just skip any DLLs we can't find, which
# will mostly be Windows system runtime stuff like kernel32.dll.
#
# The result, after manually -including the top-level .openconnect.exe.d,
# is that we have a full transitive list of required non-system DLLs
# in the $(DLLS) variable. Which will contain duplicates, hence the
# use of $(sort) when writing it out to file-list.txt.

# Defaults for manual invocation.
DLL_EXECUTABLES ?= openconnect.exe wintun.dll $(EXTRA_EXECUTABLES)
MINGW ?= x86_64-w64-mingw32
OBJDUMP ?= $(MINGW)-objdump
bindir ?= /usr/$(MINGW)/sys-root/mingw/bin
V ?= 0

AM_V_LISTDLLS = $(am__v_LISTDLLS_$(V))
am__v_LISTDLLS_ = $(am__v_LISTDLLS_$(AM_DEFAULT_VERBOSITY))
am__v_LISTDLLS_0 = @echo "  LISTDLLS" $<;
am__v_LISTDLLS_1 =

LISTDLLS_CMD = $(AM_V_LISTDLLS) \
	( echo "DLLS += $<" ; echo "file-list.txt: $@ $<" ; \
	  $(OBJDUMP) -p "$<" | sed -n '/DLL Name:/{s%^.*DLL Name: \(Qt.*\)\?\(.*\)\?%-include .\1\L\2.d%;p}' ) > $@

VPATH = $(bindir) $(EXTRA_DLLDIRS)

.%.d: .libs/%
	$(LISTDLLS_CMD)

.%.d: %
	$(LISTDLLS_CMD)

include $(patsubst %,.%.d,$(DLL_EXECUTABLES))

AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY))
am__v_GEN_0 = @echo "  GEN     " $@;
am__v_GEN_1 =

file-list.txt:
	$(AM_V_GEN) for dll in $(sort $(DLLS)); do echo "$${dll}"; done > $@
