#!/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
other_flavour := $(version_major)
else
flavour := $(version_major)
other_flavour := $(version_major)-server
endif
pkg_meta         := nvidia-driver-$(flavour)
pkg_meta_open    := $(pkg_meta)-open
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),arm64)
DKMS_disabled_modules :=
arm64_only :=
arm64_excluded := \#
else
arm64_only := \#
arm64_excluded :=
endif

ifeq ($(DEB_HOST_ARCH),ppc64el)
DKMS_disabled_modules :=
ppc64el_only :=
ppc64el_excluded := \#
else
ppc64el_only := \#
ppc64el_excluded :=
endif

# i386 binaries are shipped in amd64
# Or could use ARCH_LIST to unpack all arches
ifeq ($(DEB_HOST_ARCH),i386)
unpack-stamp: NVIDIA-Linux-amd64
else
unpack-stamp: NVIDIA-Linux-$(DEB_HOST_ARCH)
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: prepare patch
prepare: unpack-stamp compare-copyright-license
patch: prepare

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

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

# 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),NVIDIA-Linux-$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

override_dh_compress:
	dh_compress -Xsupported-gpus.json

override_dh_installinit:
override_dh_shlibdeps:

override_dh_installsystemd:

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

.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|version|*|g" | \
				sed -e "s|flavour|*|g"`; \
		rm -f $$old; done
	# Create important strings
	for i in debian/templates/control.in; do \
		dest=`echo $$i | sed -e "s|templates\/||g" | \
				 sed -e "s|\.in\$$||g" | \
				 sed -e "s|version|$(version)|g" | \
				 sed -e "s|flavour|$(flavour)|g"`; \
		sed -e "s|#LIBDIR#|$(libdir)|g"         \
			-e "s|#ARMHF_ONLY#|$(armhf_only)|g" \
			-e "s|#ARM64_ONLY#|$(arm64_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|#ARM64_EXCLUDED#|$(arm64_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|#OTHER_FLAVOUR#|$(other_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-$(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_kern_download_url	= $(or $(HTTPURL_PREFIX_$(strip $1)),$(HTTPURL_PREFIX))/$(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))

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:
	dh_gencontrol -- -V'nvidia:Version=$(version)'

generate-modaliases:
	# Generate modaliases for the restricted drivers manager
	mkdir -p $(CURDIR)/debian/$(pkg_meta)-modaliases/usr/share/jockey/modaliases/
	mkdir -p $(CURDIR)/debian/$(pkg_meta_open)-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

	python3 $(CURDIR)/debian/nvidia_supported \
		$(pkg_module) $(pkg_meta_open) \
		NVIDIA-Linux/supported-gpus/supported-gpus.json --open \
		> $(CURDIR)/debian/$(pkg_meta_open).modaliases
	# Take additional card ids from a text file
	# Generate a modalias for each ID
	@set -e -x ; \
	while read line; do \
		echo $$line | grep -Eq '^#.*' && 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
	while read line; do \
		echo $$line | grep -Eq '^#.*' && 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_open)"; \
		done; \
	done < $(CURDIR)/debian/additional_card_ids_open >>$(CURDIR)/debian/$(pkg_meta_open).modaliases
	dh_modaliases
	rm -f $(CURDIR)/debian/$(pkg_meta).modaliases
	rm -f $(CURDIR)/debian/$(pkg_meta_open).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
	# Use different a download function for kernelsrc
	if [ -n "$(findstring NVIDIA,$(NVIDIA_FILENAME_$*))" ]; then \
		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/ ; \
	else \
		ln -v $(CACHE)/$(NVIDIA_FILENAME_$*) get-orig-source/ 2>/dev/null || \
		    wget $(call get_kern_download_url,$*) -P get-orig-source/ || \
		    cp $*/$(NVIDIA_FILENAME_$*) get-orig-source/ ; \
	fi

	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="@123456789" \
	        --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
