#!/usr/bin/make -f

DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk

ifneq (,$(findstring amd64,$(DEB_BUILD_ARCH)))
export DEB_BUILD_MAINT_OPTIONS = hardening=+fortify,-stackprotector,+relro,+bindnow,-pie
else
export DEB_BUILD_MAINT_OPTIONS = hardening=+fortify,-stackprotector,+relro,+bindnow,+pie
endif

devi := $(shell lsb_release -r -s | cut -d '.'  -f1)
ifeq ($(shell if [ $(devi) -gt 7 ] ; then echo gt ; else echo lt ; fi),gt)
   DEBVE2=yes
else
   DEBVE2=no
endif

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
DEB_HOST_GNU_TYPE   ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE)
DEB_BUILD_GNU_TYPE  ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
DEB_HOST_ARCH = $(shell dpkg-architecture -qDEB_HOST_ARCH)

ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
    CFLAGS += -O0
else

OPTI_FLAGS_LIBONLY := -funswitch-loops -fpredictive-commoning -fgcse-after-reload -ftree-vectorize -fomit-frame-pointer
ifeq ($(DEB_HOST_ARCH),i386)
ifeq ($(DEBVE2),yes)
    OPTI_FLAGS_LIBONLY += -march=i686 -mtune=generic -mmmx -msse -mfpmath=sse -fexcess-precision=fast 
else
    OPTI_FLAGS_LIBONLY += -march=i586 -mtune=generic -mmmx -fexcess-precision=fast 
endif
else
ifeq ($(DEB_HOST_ARCH),i486)
ifeq ($(DEBVE2),yes)
    OPTI_FLAGS_LIBONLY += -march=i686 -mtune=generic -mmmx -msse -mfpmath=sse -fexcess-precision=fast 
else
    OPTI_FLAGS_LIBONLY += -march=i586 -mtune=generic -mmmx -fexcess-precision=fast 
endif
endif
endif

ifeq ($(DEB_HOST_ARCH),amd64)
    OPTI_FLAGS_LIBONLY += -mmmx -msse -msse2 -mfpmath=sse -fexcess-precision=fast 
endif

CPPFLAGS= -O3 $(OPTI_FLAGS_LIBONLY)
export CPPFLAGS= -O3 $(OPTI_FLAGS_LIBONLY)
CFLAGS= -O3 $(OPTI_FLAGS_LIBONLY)
export CFLAGS= -O3 $(OPTI_FLAGS_LIBONLY)
CXXFLAGS= -O3 $(OPTI_FLAGS_LIBONLY)
export CXXFLAGS= -O3 $(OPTI_FLAGS_LIBONLY)

endif



DESTDIR = $(CURDIR)/debian/quakespasm

ifeq ($(shell if [ $(devi) -gt 6 ] ; then echo gt ; else echo lt ; fi),gt)
   DEBVE=yes
else
   DEBVE=no
endif

ifeq ($(shell if [ $(devi) -gt 8 ] ; then echo gt ; else echo lt ; fi),gt)
   DEBVE3=yes
else
   DEBVE3=no
endif

ifeq ($(DEBVE2),yes)
SDL2YES="USE_SDL2=1"
endif


%:
	dh $@

ifeq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
maybe_debug = DEBUG=0
else
maybe_debug = DEBUG=1
endif

override_dh_auto_clean:
	make -C Quake clean

override_dh_auto_build:
	make -C Quake \
		$(maybe_debug) \
		STRIP=": do not strip:" \
		DFLAGS="$(CPPFLAGS)" \
		DO_USERDIRS=1 \
		USE_CODEC_FLAC=1 \
		USE_CODEC_OPUS=1 \
		USE_CODEC_MIKMOD=1 \
		USE_CODEC_UMX=1 $(SDL2YES)
	make -C Misc/qs_pak

override_dh_strip:
ifeq ($(DEBVE3),yes)
	dh_strip --ddeb-migration='quakespasm-dbg (<< 0.90.1+dfsg-2~)'
endif
