#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
export NO_DOC_PKG_MANGLE=1

include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/pkg-info.mk

include debian/rules.defs
XORG_ABI_LIST		?=
XORG_BOUND		?=

version			 = $(DEB_VERSION_UPSTREAM)
NVIDIA_RELEASE   = $(version)
version_major		 = $(firstword $(subst ., ,$(version)))

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

ifeq ($(DEB_HOST_ARCH),amd64)
OTHER_ARCH := $(shell echo "$(DEB_HOST_MULTIARCH)" | sed s/x86_64/i386/)
else
OTHER_ARCH := \#
endif


# Hack for pbuild
PATH := $(PATH):/usr/sbin

# Package names
PKG_flavour          := $(version_major)
PKG_driver           := nvidia-$(PKG_flavour)
PKG_driver_dev       := $(PKG_driver)-dev
PKG_driver_uvm       := $(PKG_driver)-uvm
PKG_version          := $(shell dpkg-parsechangelog | awk -F' ' '/^Version:/ {print $$2}' | awk -F- '{print $$1}')
PKG_version          := $(shell echo $(PKG_version) | sed s/.*\.really\.//g)
PKG_source           := $(shell dpkg-parsechangelog | sed -n 's/^Source: //p')
PKG_module           := nvidia
PKG_libcuda1         := libcuda1-$(PKG_flavour)
PKG_libopencl1       := nvidia-libopencl1-$(PKG_flavour)
PKG_opencl_icd       := nvidia-opencl-icd-$(PKG_flavour)


# Priority of the alternative
alt_priority         := 8604
pm_alt_priority      := 8603

bindir               := /usr/bin
datadir              := /usr/share
nvidia_share         := /usr/share/nvidia
PKG_datadir          := $(datadir)/$(PKG_driver)
libdir               := /usr/lib
libdir32             := /usr/lib32
libdir_multiarch     := $(libdir)/$(DEB_HOST_MULTIARCH)
libdir_multiarch_other := $(libdir)/$(OTHER_ARCH)
includedir           := /usr/include
sysconfdir           := /etc
PKG_libdir           := $(libdir)/$(PKG_driver)
PKG_libdir32         := $(libdir32)/$(PKG_driver)
mesa_libdir          := $(libdir)/$(DEB_HOST_MULTIARCH)/mesa
mesa_egl_libdir      := $(libdir)/$(DEB_HOST_MULTIARCH)/mesa-egl
mesa_libdir_other    := $(libdir)/$(OTHER_ARCH)/mesa
mesa_egl_libdir_other := $(libdir)/$(OTHER_ARCH)/mesa-egl
xorg_libdir          := $(libdir)/xorg
xorg_extra_path      := $(libdir)/$(DEB_HOST_MULTIARCH)/xorg
xorg_extra_modules   := $(xorg_extra_path)/extra-modules
xorg_extensionsdir   := $(xorg_libdir)/modules/extensions
PKG_driversdir       := $(libdir)/$(PKG_driver)/xorg
PKG_extensionsdir    := $(PKG_driversdir)
PKG_bindir           := $(PKG_libdir)/bin
PKG_configdir        := $(PKG_libdir)
ld_so_conf_dir       := $(PKG_configdir)
ld_so_conf_file      := ld.so.conf
alt_ld_so_conf_file  := alt-ld.so.conf
ld_so_conf_path      := $(ld_so_conf_dir)/$(ld_so_conf_file)
alt_ld_so_conf_path  := $(ld_so_conf_dir)/$(alt_ld_so_conf_file)

#Prime
PKG_prime            := $(PKG_driver)-prime
PKG_prime_libdir     := $(libdir)/$(PKG_prime)
pm_ld_so_conf_path      := $(PKG_prime_libdir)/ld.so.conf-pm
pm_alt_ld_so_conf_path  := $(PKG_prime_libdir)/alt-ld.so.conf-pm

mandir               := /usr/share/man/man1
PKG_bugdir           := /usr/share/bug/$(PKG_driver)
PKG_vdpaudir         := $(PKG_libdir)/vdpau
PKG_tlsdir           := $(PKG_libdir)/tls
PKG_vdpaudir32       := $(PKG_libdir32)/vdpau
PKG_tlsdir32         := $(PKG_libdir32)/tls
vdpaudir             := $(libdir)/vdpau
tlsdir               := $(libdir)/tls
vdpaudir32           := $(libdir32)/vdpau
tlsdir32             := $(libdir32)/tls
grub_blacklistdir    := /usr/share/grub-gfxpayload-lists/blacklist

ifeq ($(DEB_HOST_ARCH),amd64)
DKMS_disabled_modules :=
else
DKMS_disabled_modules := nvidia-uvm
endif

# This is a hack to make sure that
# the blacklist file is available
# early in the boot process when
# /usr is on a separate partition.
# See LP: #538071.
PKG_libconfdir := /lib/$(PKG_driver)

dirname              := NVIDIA-Linux

ifeq ($(DEB_HOST_ARCH),amd64)
DKMS_disabled_modules :=
amd64_only :=
i386_only := \#
else
DKMS_disabled_modules := nvidia-uvm
amd64_only := \#
endif

ifeq ($(DEB_HOST_ARCH),i386)
amd64_only := \#
i386_only :=
endif

comma		 = ,
xorg_depends	 = $(foreach abi, $(XORG_ABI_LIST), xorg-video-abi-$(abi) |)
xorg_depends	+= $(comma) xserver-xorg-core $(XORG_BOUND)
xorg_provides	 = xorg-driver-video


.PHONY: autogen prepare patch
autogen: $(AUTOGEN)
prepare: autogen unpack-stamp compare-copyright-license
#prepare: autogen unpack-stamp nvidia.ids compare-copyright-license
patch: prepare

NVIDIA-Linux-%:
	sh $*/${NVIDIA_FILENAME_$*} --extract-only
	ln -s ${NVIDIA_DIRNAME_$*} $@
	#gunzip $@/*.1.gz

# Unpack all architectures, we may need files from all of them.
unpack-stamp: NVIDIA-Linux-amd64
	dh_testdir
	ln -s NVIDIA-Linux-amd64 NVIDIA-Linux
	#QUILT_PATCHES=debian/patches QUILT_SERIES=series-postunpack quilt --quiltrc /dev/null push -a || test $$? = 2
	ls -al
	touch $@

generate-nvidia-icd-json:
	# This is for GLVND LibGL libraries
	sed 's/__NV_VK_ICD__/libGLX_nvidia.so.0/g'  NVIDIA-Linux/nvidia_icd.json.template > \
		NVIDIA-Linux/nvidia_icd.json
	# non-GLVND only
	mkdir NVIDIA-Linux/nonglvnd || true
	sed 's/__NV_VK_ICD__/libGL.so.1/g'  NVIDIA-Linux/nvidia_icd.json.template > \
        NVIDIA-Linux/nonglvnd/nvidia_icd.json

# Reformat the LICENSE to the format needed for debian/copyright.
LICENSE.txt: unpack-stamp
	sed -e 's/^ *//; s/ *$$//; s/^$$/./; s/^/ /;' NVIDIA-Linux/LICENSE > $@

# Compare the license in debian/copyright with the LICENSE shipped in the archive.
compare-copyright-license: LICENSE.txt
	sed -e '1,/^License: NVIDIA-graphics-drivers/d; 1,/^License: NVIDIA-graphics-drivers$$/d; /^$$\|^Comment:$$/,$$d; /^ \.$$/d' debian/copyright > copyright.tmp
	sed -e '/^ \.$$/d' LICENSE.txt > LICENSE.tmp
	diff -w copyright.tmp LICENSE.tmp
	rm -f copyright.tmp LICENSE.tmp

%:
	dh $@

override_dh_auto_clean:
	rm -fr .pc
	rm -f NVIDIA-Linux
	rm -fr $(foreach a,$(ARCH_LIST),$a/NVIDIA-Linux-$a $a/$(NVIDIA_DIRNAME_$a))
	rm -fr kernel-source-tree
	rm -f nvidia.ids nv-kernel.ids nv-readme.ids pci.ids.nvidia*
	rm -f LICENSE.txt LICENSE.tmp copyright.tmp
	test ! -d debian/po || debconf-updatepo
	rm -f debian/$(PKG_driver).substvars
	rm -f debian/dkms.conf

override_dh_clean: regen-from-templates
	dh_clean
	rm -f $(AUTOCLEAN)
	$(MAKE) -f debian/rules $(AUTOKEEP)

override_dh_auto_configure: prepare regen-from-templates generate-nvidia-icd-json remove-stack-markings

override_dh_install: generate-modaliases
	# Use our custom dkms.conf file
	cp -f $(CURDIR)/debian/dkms_nvidia.conf $(CURDIR)/debian/dkms.conf

ifeq ($(DEB_HOST_ARCH),amd64)
	# Make sure the UVM module is built
	cat $(CURDIR)/debian/dkms.conf.fragment >> $(CURDIR)/debian/dkms.conf
endif

	dh_install

override_dh_installinit:
	dh_installinit -p $(PKG_driver) --name nvidia-persistenced
	dh_installinit --remaining

remove-stack-markings:
	# Disable the stack markings of binaries for security reasons.
	# See (LP: #409456)
	find NVIDIA-Linux/ -name *.so* | xargs -n1 execstack -c

	# Disable the stack markings of other binaries (only for the current arch)
	#   Note: don't use for loops or pass more than 1 argument to execstack
	#         or it will fail.
	execstack -c NVIDIA-Linux/nvidia-xconfig || true
	execstack -c NVIDIA-Linux/nvidia-smi || true
	execstack -c NVIDIA-Linux/nvidia-persistenced || true

override_dh_shlibdeps:
	LD_LIBRARY_PATH=/$(libdir):$(CURDIR)/debian/$(PKG_driver)$(PKG_libdir):$(LD_LIBRARY_PATH) dh_shlibdeps -Xlib32 -Xi386

# Do not run dh_strip here.  The NVIDIA license says:
#
#     2.1.2 Linux/FreeBSD Exception.  Notwithstanding the foregoing terms of
#     Section 2.1.1, SOFTWARE designed exclusively for use on the Linux or
#     FreeBSD operating systems, or other operating systems derived from the
#     source code to these operating systems, may be copied and
#     redistributed, provided that the binary files thereof are not modified
#     in any way (except for unzipping of compressed files).
#
# Stripping the binary modules would constitute modifying the binary files
# in a way other than unzipping of compressed files.
override_dh_strip:
override_dh_strip_nondeterminism:


# Make the initramfs scripts executable
override_dh_fixperms:
	dh_fixperms
	chmod 755 $(CURDIR)/debian/framebuffer-nvidia
	chmod 755 $(CURDIR)/debian/copy-nvidia-options

############################################################################

.PHONY: regen-from-templates
regen-from-templates:
	# Get rid of files belonging to different flavours
	for i in debian/templates/*.in; do \
		old=`echo $$i | sed -e "s|templates\/||g" | \
				sed -e "s|\.in\$$||g" | \
				sed -e "s|nvidia-graphics-drivers|nvidia-*|g" | \
				sed -e "s|flavour|*|g"`; \
		rm -f $$old; done
	# Create important strings
	for i in debian/templates/*.in; do \
		dest=`echo $$i | sed -e "s|templates\/||g" | \
				 sed -e "s|\.in\$$||g" | \
				 sed -e "s|nvidia-graphics-drivers|$(PKG_driver)|g" | \
				 sed -e "s|flavour|$(PKG_flavour)|g"`; \
		sed -e "s|#LIBDIR#|$(libdir)|g"         \
			-e "s|#I386_ONLY#|$(i386_only)|g" \
			-e "s|#AMD64_ONLY#|$(amd64_only)|g" \
			-e "s|#NVEXCLUDEMODULES#|$(DKMS_disabled_modules)|g" \
			-e "s|#FLAVOUR#|$(PKG_flavour)|g" \
			-e "s|#DRIVERNAME#|$(PKG_driver)|g" \
			-e "s|#DRIVERDEVNAME#|$(PKG_driver_dev)|g" \
			-e "s|#DRIVERUVMNAME#|$(PKG_driver_uvm)|g" \
			-e "s|#DRIVERSRCNAME#|$(PKG_source)|g" \
			-e "s|#MODULENAME#|$(PKG_module)|g" \
			-e "s|#VERSION#|$(version)|g" \
			-e "s|#MODULENAME#|$(version)|g" \
			-e "s|#DEB_HOST_MULTIARCH#|$(DEB_HOST_MULTIARCH)|g" \
			-e "s|#LIBDIR32#|$(libdir32)|g"     \
			-e "s|#LIBDIRMULTIARCH#|$(libdir_multiarch)|g" \
			-e "s|#LIBDIRMULTIARCHOTHER#|$(libdir_multiarch_other)|g" \
			-e "s|#BINDIR#|$(bindir)|g"         \
			-e "s|#SYSCONFDIR#|$(sysconfdir)|g" \
			-e "s|#MANDIR#|$(mandir)|g" \
			-e "s|#LDSOCONF#|$(ld_so_conf_path)|g" \
			-e "s|#LDSOCONFDIR#|$(ld_so_conf_dir)|g" \
			-e "s|#ALTLDSOCONF#|$(alt_ld_so_conf_path)|g" \
			-e "s|#PMLDSOCONF#|$(pm_ld_so_conf_path)|g" \
			-e "s|#PMALTLDSOCONF#|$(pm_alt_ld_so_conf_path)|g" \
			-e "s|#ALTPRIORITY#|$(alt_priority)|g" \
			-e "s|#PMALTPRIORITY#|$(pm_alt_priority)|g" \
			-e "s|#DATADIR#|$(datadir)|g" \
			-e "s|#PKGDATADIR#|$(PKG_datadir)|g" \
			-e "s|#PKGCONFIGDIR#|$(PKG_configdir)|g" \
			-e "s|#PKGBINDIR#|$(PKG_bindir)|g" \
			-e "s|#PKGLIBDIR#|$(PKG_libdir)|g" \
			-e "s|#PKGLIBDIR32#|$(PKG_libdir32)|g" \
			-e "s|#PKGPRIMELIBDIR#|$(PKG_prime_libdir)|g" \
			-e "s|#MESALIBDIR#|$(mesa_libdir)|g" \
			-e "s|#MESALIBDIROTHER#|$(mesa_libdir_other)|g" \
			-e "s|#MESAEGLLIBDIR#|$(mesa_egl_libdir)|g" \
			-e "s|#MESAEGLLIBDIROTHER#|$(mesa_egl_libdir_other)|g" \
			-e "s|#PKGDRIVERSDIR#|$(PKG_driversdir)|g" \
			-e "s|#XORGEXTRA#|$(xorg_extra_modules)|g" \
			-e "s|#XORGEXTRAPATH#|$(xorg_extra_path)|g" \
			-e "s|#NVIDIAEXTENSION#|$(PKG_extensionsdir)|g" \
			-e "s|#XORGEXTENSIONSDIR#|$(xorg_extensionsdir)|g" \
			-e "s|#FLAVOUR#|$(PKG_flavour)|g" \
			-e "s|#LIBCUDA1#|$(PKG_libcuda1)|g" \
			-e "s|#LIBOPENCL1#|$(PKG_libopencl1)|g" \
			-e "s|#OPENCLICD#|$(PKG_opencl_icd)|g" \
			-e "s|#DIRNAME#|$(dirname)|g" \
			-e "s|#INCLUDEDIR#|$(includedir)|g" \
			-e "s|#URL#|$(url)|g" \
			-e "s|#VDPAUDIR#|$(vdpaudir)|g" \
			-e "s|#VDPAUDIR32#|$(vdpaudir32)|g" \
			-e "s|#TLSDIR#|$(tlsdir)|g" \
			-e "s|#PKGVDPAUDIR#|$(PKG_vdpaudir)|g" \
			-e "s|#PKGVDPAUDIR32#|$(PKG_vdpaudir32)|g" \
			-e "s|#PKGTLSDIR#|$(PKG_tlsdir)|g" \
			-e "s|#PKGTLSDIR32#|$(PKG_tlsdir32)|g" \
			-e "s|#PKGLIBCONFDIR#|$(PKG_libconfdir)|g" \
			-e "s|#GRUBBLKLISTDIR#|$(grub_blacklistdir)|g" \
			-e "s|#DEB_HOST_MULTIARCH#|$(DEB_HOST_MULTIARCH)|g" \
			-e "s|#OTHER_ARCH#|$(OTHER_ARCH)|g" \
			-e "s|#NVIDIASHARE#|$(nvidia_share)|g" \
			-e "s|#ARM_EXCLUDED#|$(arm_excluded)|g" \
			$$i > $$dest;      \
	done


############################################################################

CACHE			?= ../.cache
ORIGDIR			?= nvidia-graphics-drivers-$(version_major).orig
TARBALL_BASE		?= nvidia-graphics-drivers-$(version_major)_$(NVIDIA_RELEASE).orig
TARBALL_SUFFIX		?= .tar.gz
TARBALL			?= $(TARBALL_BASE)$(TARBALL_SUFFIX)
ORIGDIR.empty		?= $(ORIGDIR)
TARBALL.empty		?= $(TARBALL)

# $1 = arch
get_download_url	 = $(or $(HTTPURL_PREFIX_$(strip $1)),$(HTTPURL_PREFIX))/$(HTTPURL_ARCHDIR_$(strip $1))/$(NVIDIA_RELEASE)/$(NVIDIA_FILENAME_$(strip $1))
get_origdir		 = $(or $(ORIGDIR.$(strip $1)),$(ORIGDIR)-$(strip $1))
get_tarball		 = $(or $(TARBALL.$(strip $1)),$(TARBALL_BASE)-$(strip $1)$(TARBALL_SUFFIX))

override_dh_gencontrol:
	dh_gencontrol -- -V'nvidia:Version=$(version)' \
		-V'nvidia:xorgDepends=$(xorg_depends)' \
		-V'nvidia:xorgProvides=$(xorg_provides)'

generate-modaliases:
	# Generate modaliases for the restricted drivers manager
	mkdir -p $(CURDIR)/debian/$(PKG_driver)-modaliases/usr/share/jockey/modaliases/
	sh -e $(CURDIR)/debian/nvidia_supported \
		$(PKG_module) $(PKG_driver) \
		NVIDIA-Linux/README.txt \
		> $(CURDIR)/debian/$(PKG_driver).modaliases
	# Take additional card ids from a text file
	while read id sid; do \
		if [ -z $$sid ]; then \
			printf 'alias pci:v%08Xd%08Xsv*sd*bc03sc*i* %s %s\n' \
			0x10de "0x$$id" "$(PKG_module)" "$(PKG_driver)" \
		;else \
			printf 'alias pci:v%08Xd%08Xsv*sd%08Xbc03sc*i* %s %s\n' \
			0x10de "0x$$id" "0x$$sid" "$(PKG_module)" "$(PKG_driver)" \
		;fi \
	done <$(CURDIR)/debian/additional_card_ids >>$(CURDIR)/debian/$(PKG_driver).modaliases
	dh_modaliases
	rm -f $(CURDIR)/debian/$(PKG_driver).modaliases

get-orig-source-prepare:
	$(RM) -r get-orig-source
	mkdir get-orig-source

get-orig-source-prepare/%: get-orig-source-prepare
	$(RM) $(call get_tarball,$*)
	mkdir get-orig-source/$(call get_origdir,$*)

get-orig-source-download/%: get-orig-source-prepare
	ln -v $(CACHE)/$(NVIDIA_FILENAME_$*) get-orig-source/ 2>/dev/null || \
		wget $(call get_download_url,$*) -P get-orig-source/
	if [ -d $(CACHE) ] && [ ! -f $(CACHE)/$(NVIDIA_FILENAME_$*) ]; then \
		ln -v get-orig-source/$(NVIDIA_FILENAME_$*) $(CACHE) ; fi

get-orig-source-files/%: get-orig-source-prepare/% get-orig-source-download/%
	@set -e -x ; \
	    cd get-orig-source ; \
		rm -f ../$*/*.run; mkdir ../$* || true; cp $(NVIDIA_FILENAME_$*) ../$*/; \
	    mv $(NVIDIA_FILENAME_$*) $(call get_origdir,$*)/ ; \
	    chmod 0755 $(call get_origdir,$*)/* ; \
	    touch $(call get_origdir,$*).stamp -r $$(ls -tr $$(find $(call get_origdir,$*) -type f) | tail -n 1)

get-orig-source-pack/%: get-orig-source-files/%
	@set -e -x ; \
	    cd get-orig-source ; \
	    tar cv \
	        --clamp-mtime --mtime="./$(call get_origdir,$*).stamp" \
	        --sort=name \
		--owner=root --group=src \
		$(call get_origdir,$*) \
		| gzip -n -9 > $(call get_tarball,$*) ; \
	    touch $(call get_tarball,$*) -r $(call get_origdir,$*).stamp
	mv get-orig-source/$(call get_tarball,$*) .

get-orig-source-files/empty: get-orig-source-prepare/empty $(foreach a,$(ARCH_LIST),get-orig-source-pack/$a)
	touch get-orig-source/$(call get_origdir,empty).stamp -r $$(ls -tr $(foreach a,$(ARCH_LIST),$(call get_tarball,$a)) | tail -n 1)

.PHONY: get-orig-source
get-orig-source: get-orig-source-pack/empty
	rm -rf get-orig-source
