#!/usr/bin/make -f

%:
	dh $@

# Select winebuild-development
export WINEBUILD := /usr/bin/winebuild-development

# 32 or 64
DEB_BUILD_ARCH_BITS=$(shell dpkg-architecture -qDEB_BUILD_ARCH_BITS)

# The name of the build-*.txt profile to choose
BUILD_NAME = win$(DEB_BUILD_ARCH_BITS)

# The directory in which we will build
BUILD_DIR   = build-$(BUILD_NAME)

# DEST_DIR is what we install to /usr/lib/dxvk
DEST_DIR    = dxvk
INSTALL_DIR = $(CURDIR)/$(DEST_DIR)/wine$(DEB_BUILD_ARCH_BITS)-development

export DEB_BUILD_MAINT_OPTIONS := hardening=+all
export CFLAGS_MESON := $(shell dpkg-buildflags --get CFLAGS)
export CPPFLAGS_MESON := $(shell dpkg-buildflags --get CPPFLAGS)
export CXXFLAGS_MESON := $(shell dpkg-buildflags --get CXXFLAGS)
# disabled, fails with: unrecognized option '-z'
#export LDFLAGS_MESON=$(shell dpkg-buildflags --get LDFLAGS)
export LDFLAGS=

# disabled, even with workarounds it does not work
# see https://sourceware.org/bugzilla/show_bug.cgi?id=12762
#ifeq (,$(findstring nolto,$(DEB_BUILD_OPTIONS)))
#  CFLAGS_MESON += -flto
#  CPPFLAGS_MESON += -flto
#  CXXFLAGS_MESON += -flto
#  LDFLAGS_MESON += -flto -fuse-linker-plugin -Wl,-allow-multiple-definition -flto-partition=none
#endif

# prepare replacement
CFLAGS_MESON := $(shell echo $(CFLAGS_MESON) | sed -r "s/ ?([^ ]+)/, '\1'/g")
CPPFLAGS_MESON := $(shell echo $(CPPFLAGS_MESON) | sed -r "s/ ?([^ ]+)/, '\1'/g")
CXXFLAGS_MESON := $(shell echo $(CXXFLAGS_MESON) | sed -r "s/ ?([^ ]+)/, '\1'/g")
#LDFLAGS_MESON := $(shell echo $(LDFLAGS_MESON) | sed -r "s/ ?([^ ]+)/, '\1'/g")

DEB_BUILD_MULTIARCH=$(shell dpkg-architecture -qDEB_BUILD_MULTIARCH)

# Meson flags
MESON_FLAGS = --buildtype release \
               --cross-file build-$(BUILD_NAME).txt.gen \
               --prefix $(INSTALL_DIR) \
               --bindir . \
               --libdir . \
               -Dwine_libdir=/usr/lib/$(DEB_BUILD_MULTIARCH)/wine-development/ \
               $(BUILD_DIR)

override_dh_auto_configure:
	echo "blhc: ignore-line-regexp: C\+\+ linker for the build machine: .*"
	echo "MESON_FLAGS: $(MESON_FLAGS)"
	cat build-$(BUILD_NAME).txt | envsubst >build-$(BUILD_NAME).txt.gen
	meson $(MESON_FLAGS)

override_dh_auto_build:
	ninja -v -C $(BUILD_DIR)

override_dh_auto_install:
	ninja -v -C $(BUILD_DIR) install
	# we could change the install script but then the previous installations would be broken
	rename 's/\.dll$$/.dll.so/' $(INSTALL_DIR)/*.dll

override_dh_auto_clean:
	rm -rf $(BUILD_DIR)
	rm -rf $(DEST_DIR)
	rm -f build-$(BUILD_NAME).txt.gen

override_dh_shlibdeps:
	dh_shlibdeps -- -l/usr/lib/$(DEB_HOST_MULTIARCH)/wine-development
