#!/usr/bin/make -f

# enable verbose build log
export DH_VERBOSE=1

# wine build fails with pie enabled
export DEB_BUILD_MAINT_OPTIONS=hardening=+all,-pie

VERSION=$(shell dpkg-parsechangelog | grep ^Source | cut -d\  -f2 | sed s/wine//g)

DATADIR=/usr/share/wine$(VERSION)
INCLUDEDIR=/usr/include/wine$(VERSION)

MANDIR=usr/share/man
LIBDIR=usr/lib/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH)/wine$(VERSION)

# linker options
export DEB_LDFLAGS_MAINT_APPEND+=-Wl,-rpath,/$(LIBDIR)

# use freebsd-glue on kfreebsd architectures
ifeq ($(DEB_BUILD_ARCH_OS), kfreebsd)
export DEB_LDFLAGS_MAINT_APPEND+=-lfreebsd-glue
endif

# configure options
CONFLAGS=--without-hal \
         --without-v4l \
         --without-sane \
         --without-capi \
         --without-gphoto \
         --without-gstreamer \
	 --with-gnutls \
         --disable-tests \
         --libdir=/$(LIBDIR) \
         --bindir=/$(LIBDIR) \
         --mandir=/$(MANDIR) \
         --datarootdir=$(DATADIR) \
         --includedir=$(INCLUDEDIR) \
         $(shell dpkg-buildflags --export=configure) \

# enable wine64 on amd64
ifeq ($(DEB_BUILD_ARCH_CPU), amd64)
CONFLAGS+=--enable-win64
endif

# additional files to generate
INSTALLS=$(shell ls debian/*VERSION* | sed s/VERSION/$(VERSION)/)

debian/control: debian/control.in
	sed s/VERSION/$(VERSION)/g < $< > $@

debian/wine$(VERSION)%: debian/wineVERSION%
	sed s/VERSION/$(VERSION)/g < $< > $@

debian/wine32$(VERSION)%: debian/wine32VERSION%
	sed s/VERSION/$(VERSION)/g < $< > $@

debian/wine64$(VERSION)%: debian/wine64VERSION%
	sed s/VERSION/$(VERSION)/g < $< > $@

debian/libwine$(VERSION)%: debian/libwineVERSION%
	sed s/VERSION/$(VERSION)/g < $< > $@

%:
	dh $@ --parallel --with autoreconf

override_dh_auto_configure:
	ln -sf /usr/share/misc/config.sub tools
	ln -sf /usr/share/misc/config.guess tools
	dh_auto_configure -- $(CONFLAGS)

override_dh_install: $(INSTALLS)
	mkdir -p debian/tmp
	cp debian/scripts/wine debian/tmp/wine$(VERSION)
	sed 's|LIBDIR|$(LIBDIR)|g' < debian/scripts/winegcc > debian/tmp/winegcc$(DEB_BUILD_ARCH_BITS)$(VERSION)
	cp tools/winedump/README debian/tmp/README.winedump
	cp programs/winedbg/README debian/tmp/README.winedbg
	cp debian/tmp/$(LIBDIR)/winecfg debian/tmp/wineapploader
	test -f debian/tmp/$(LIBDIR)/wine-preloader || \
	    cp debian/scripts/wine-preloader debian/tmp/$(LIBDIR)
	for file in $$(find debian/tmp/$(MANDIR) -type f); do \
	    rename=$$(echo $$file | sed s/\\.1/$(VERSION)\\.1/); \
	    cp $$file $$rename || true; \
	    done
	cd debian/tmp/usr/share/man/man1 && \
	    cp winegcc.1 winegcc$(DEB_BUILD_ARCH_BITS)$(VERSION).1
	dh_install

override_dh_strip:
	dh_strip -Xwine-pthread -Xwine-kthread --dbg-package=libwine$(VERSION)-dbg

override_dh_clean:
	dh_clean -- \
	    $(INSTALLS) \
	    debian/control \
	    programs/cscript/ihost.h \
	    configure config.* tools/config.* include/config.h.in
	make -f debian/rules debian/control
