#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

SRCDIR = toonz/sources
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

# Define ARM-specific flags only for armhf to fix the 54% linker error
# This ensures amd64, aarch64, and i386 remain completely untouched.
ifeq ($(DEB_HOST_ARCH),armhf)
  EXTRA_CMAKE_FLAGS = -Dwith_gles2=ON \
                      -DOPENGL_gl_LIBRARY=/usr/lib/arm-linux-gnueabihf/libGLESv2.so \
                      -DOPENGL_opengl_LIBRARY=/usr/lib/arm-linux-gnueabihf/libGLESv2.so
endif

%:
	dh $@ --buildsystem=cmake --sourcedirectory=$(SRCDIR)

override_dh_auto_configure:
	# Patch armhf source to comment out Desktop GL calls that GLES2 doesn't have
	if [ "$(DEB_HOST_ARCH)" = "armhf" ]; then \
		sed -i 's/glPushMatrix/ \/\/glPushMatrix/g' $(SRCDIR)/toonzqt/lutcalibrator.cpp; \
		sed -i 's/glLoadIdentity/ \/\/glLoadIdentity/g' $(SRCDIR)/toonzqt/lutcalibrator.cpp; \
		sed -i 's/glPopMatrix/ \/\/glPopMatrix/g' $(SRCDIR)/toonzqt/lutcalibrator.cpp; \
	fi

	# Build modified LibTIFF first (Required)
	cd thirdparty/tiff-4.0.3 && ./configure --with-pic --disable-jbig
	$(MAKE) -C thirdparty/tiff-4.0.3 -j$(shell nproc)
	
	# Configure Main App
	# EXTRA_CMAKE_FLAGS is empty for all architectures except armhf
	dh_auto_configure --sourcedirectory=$(SRCDIR) -- \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DSUPERLU_INCLUDE_DIR=/usr/include/superlu \
		-DCMAKE_BUILD_TYPE=Release \
		-DWITH_TNL=ON \
		$(EXTRA_CMAKE_FLAGS)

override_dh_auto_install:
	dh_auto_install --sourcedirectory=$(SRCDIR) --destdir=debian/tmp
	
	if [ ! -d "debian/tmp/usr/share/opentoonz/stuff" ]; then \
		mkdir -p debian/tmp/usr/share/opentoonz; \
		cp -r stuff debian/tmp/usr/share/opentoonz/; \
	fi

override_dh_install:
	dh_install --sourcedir=debian/tmp