#!/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			 = $(shell echo $(DEB_VERSION_UPSTREAM) | sed -e's/.*\+really\.//')
debian_version	= $(shell echo $(DEB_VERSION_UPSTREAM) | sed -e's/.*\+really\.//')
NVIDIA_RELEASE   = $(version)
version_major		 = $(firstword $(subst ., ,$(version)))

# system libdir
libdir			?= usr/lib/$(DEB_HOST_MULTIARCH)

last_suffix		:= $(lastword $(subst -, ,$(DEB_SOURCE)))
ifeq ($(last_suffix),server)
flavour := $(version_major)-server
else
flavour := $(version_major)
endif
pkg_meta         := nvidia-driver-$(flavour)
pkg_driver       := nvidia-$(flavour)
xorg_driver      := xserver-xorg-video-nvidia-$(flavour)
#pkg_module       := $(shell echo "$(pkg_driver)" | sed s/\-/_/g)
pkg_module       := nvidia
pkg_kernel       := nvidia-kernel-$(flavour)

ifeq ($(DEB_HOST_ARCH),amd64)
DKMS_disabled_modules :=
amd64_only :=
amd64_excluded := \#
else
amd64_only := \#
amd64_excluded :=
endif

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

ifeq ($(DEB_HOST_ARCH),armhf)
DKMS_disabled_modules := nvidia-uvm
armhf_only :=
armhf_excluded := \#
else
armhf_only := \#
armhf_excluded :=
endif

ifeq ($(DEB_HOST_ARCH),ppc64el)
DKMS_disabled_modules :=
ppc64el_only :=
ppc64el_excluded := \#
else
ppc64el_only := \#
ppc64el_excluded :=
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: $(patsubst %,NVIDIA-Linux-%,$(ARCH_LIST))
	dh_testdir
ifeq ($(DEB_HOST_ARCH),i386)
	ln -s NVIDIA-Linux-amd64 NVIDIA-Linux
else
	ln -s NVIDIA-Linux-$(DEB_HOST_ARCH) NVIDIA-Linux
endif
	#QUILT_PATCHES=debian/patches QUILT_SERIES=series-postunpack quilt --quiltrc /dev/null push -a || test $$? = 2
	ls -al
	touch $@

generate-nvidia-icd-json:
	if [ -f NVIDIA-Linux/nvidia_icd.json.template ]; then \
		sed 's/__NV_VK_ICD__/libGLX_nvidia.so.0/g'  NVIDIA-Linux/nvidia_icd.json.template > \
			NVIDIA-Linux/nvidia_icd.json; \
	fi

# 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

build-device-create:
	rm -f $(CURDIR)/debian/device-create/ub-device-create
	cd $(CURDIR)/debian/device-create/ && $(MAKE) all || exit 1
	@echo "ub-device-create built"

%:
	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 debian/runtimepm_ids
	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
	rm -f debian/device-create/ub-device-create

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_compress:
	dh_compress -Xsupported-gpus.json

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

ifeq (,$(findstring nvidia-uvm,$(DKMS_disabled_modules)))
	# Make sure the UVM module is built
	cat $(CURDIR)/debian/dkms.conf.fragment >> $(CURDIR)/debian/dkms.conf
endif

ifeq ($(DEB_HOST_ARCH),ppc64el)
	# POWER 9 seems to need this
	sed -i 's/--user nvidia-persistenced --no-persistence-mode/--user root --persistence-mode/' \
		 $(CURDIR)/debian/nvidia-compute-utils-$(flavour).nvidia-persistenced.service
endif

	dh_install -p nvidia-compute-utils-$(flavour)
	mkdir -p $(CURDIR)/debian/nvidia-compute-utils-$(flavour)/lib/systemd
	dh_systemd_enable --name=nvidia-persistenced
	dh_install -p nvidia-kernel-common-$(flavour)

	mkdir -p $(CURDIR)/debian/nvidia-kernel-common-$(version_major)/lib/systemd
	dh_systemd_enable --name=nvidia-hibernate
	dh_systemd_enable --name=nvidia-resume
	dh_systemd_enable --name=nvidia-suspend

	mkdir -p $(CURDIR)/debian/nvidia-kernel-common-$(version_major)/lib/systemd
	dh_systemd_enable --name=nvidia-hibernate
	dh_systemd_enable --name=nvidia-resume
	dh_systemd_enable --name=nvidia-suspend

	dh_install

override_dh_installinit:
	dh_installinit --noscripts

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):$(LD_LIBRARY_PATH) dh_shlibdeps

# 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:

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

.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|flavour|$(flavour)|g"`; \
		sed -e "s|#LIBDIR#|$(libdir)|g"         \
			-e "s|#ARMHF_ONLY#|$(armhf_only)|g" \
			-e "s|#AMD64_ONLY#|$(amd64_only)|g" \
			-e "s|#I386_ONLY#|$(i386_only)|g" \
			-e "s|#PPC64EL_ONLY#|$(ppc64el_only)|g" \
			-e "s|#ARMHF_EXCLUDED#|$(armhf_excluded)|g" \
			-e "s|#AMD64_EXCLUDED#|$(amd64_excluded)|g" \
			-e "s|#I386_EXCLUDED#|$(i386_excluded)|g" \
			-e "s|#PPC64EL_EXCLUDED#|$(ppc64el_excluded)|g" \
			-e "s|#NVEXCLUDEMODULES#|$(DKMS_disabled_modules)|g" \
			-e "s|#FLAVOUR#|$(flavour)|g" \
			-e "s|#DRIVERNAME#|$(pkg_driver)|g" \
			-e "s|#VERSION#|$(version)|g" \
			-e "s|#DEBIAN_VERSION#|$(debian_version)|g" \
			-e "s|#MODULENAME#|$(version)|g" \
			-e "s|#DEB_HOST_MULTIARCH#|$(DEB_HOST_MULTIARCH)|g" \
			$$i > $$dest;      \
	done

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

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

# $1 = arch
ifneq (,$(findstring -server,$(flavour)))
    # Found
get_download_url	 = $(HTTPURL_PREFIX_tesla)/$(NVIDIA_RELEASE)/$(NVIDIA_FILENAME_$(strip $1))
else
get_download_url	 = $(or $(HTTPURL_PREFIX_$(strip $1)),$(HTTPURL_PREFIX))/$(HTTPURL_ARCHDIR_$(strip $1))/$(NVIDIA_RELEASE)/$(NVIDIA_FILENAME_$(strip $1))
endif

get_origdir		 = $(or $(ORIGDIR.$(strip $1)),$(ORIGDIR)-$(strip $1))
get_tarball		 = $(or $(TARBALL.$(strip $1)),$(TARBALL_BASE)-$(strip $1)$(TARBALL_SUFFIX))

update-runtimepm-ids:
	python3 $(CURDIR)/debian/add-ids-to-json-db \
		NVIDIA-Linux/supported-gpus/supported-gpus.json \
		$(CURDIR)/debian/additional_runtimepm_ids \
		NVIDIA-Linux/supported-gpus/supported-gpus-mod.json

generate-runtimepm-aliases: update-runtimepm-ids
	python3 $(CURDIR)/debian/pm-aliases-gen \
		NVIDIA-Linux/supported-gpus/supported-gpus-mod.json > $(CURDIR)/debian/runtimepm_ids
	rm -f NVIDIA-Linux/supported-gpus/supported-gpus-mod.json

override_dh_gencontrol: generate-runtimepm-aliases
	dh_gencontrol -- -V'nvidia:Version=$(version)' \
		-V'nvidia:xorgDepends=$(xorg_depends)' \
		-V'nvidia:xorgProvides=$(xorg_provides)' \
		-V'nvidia:pm-modaliases=$(shell cat $(CURDIR)/debian/runtimepm_ids)'

generate-modaliases:
	# Generate modaliases for the restricted drivers manager
	mkdir -p $(CURDIR)/debian/$(pkg_meta)-modaliases/usr/share/jockey/modaliases/
	python3 $(CURDIR)/debian/nvidia_supported \
		$(pkg_module) $(pkg_meta) \
		NVIDIA-Linux/supported-gpus/supported-gpus.json \
		> $(CURDIR)/debian/$(pkg_meta).modaliases
	# Take additional card ids from a text file
	# Generate a modalias for each ID
	@set -e -x ; \
	while read line; do \
		[ "$$line"=~"#.*" ] && continue; \
		for id in $$line; do \
			printf 'alias pci:v%08Xd%08Xsv*sd*bc03sc*i* %s %s\n' \
				0x10de "0x$$id" "$(pkg_module)" "$(pkg_meta)"; \
		done; \
	done < $(CURDIR)/debian/additional_card_ids >>$(CURDIR)/debian/$(pkg_meta).modaliases
	dh_modaliases
	rm -f $(CURDIR)/debian/$(pkg_meta).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/ || cp $*/$(NVIDIA_FILENAME_$*) 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
