#!/usr/bin/make -f

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

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

NVIDIA_RELEASE		:= $(shell dpkg-parsechangelog | sed -nr '/^Version:/s/Version: (.*:)?(.*)-(.*)/\2/p')
include debian/rules.defs
NVIDIA_LEGACY		?=
WATCH_VERSION		?= $(NVIDIA_LEGACY)
WATCH_PATTERN		?=
XORG_ABI_LIST		?=
XORG_BOUND		?=
MULTIARCH		?=
BACKPORT		?=
NVIDIA_SETTINGS		?= nvidia-settings
version			 = $(NVIDIA_RELEASE)
legacy			 = $(if $(NVIDIA_LEGACY),-legacy-$(NVIDIA_LEGACY)xx)
legacy_description	 = $(if $(NVIDIA_LEGACY), ($(NVIDIA_LEGACY)xx legacy version))
perfkit			 =
watch_pattern		 = $(or $(WATCH_PATTERN),$(if $(WATCH_VERSION),$(WATCH_VERSION)(?:\.[\d\.\-]+)?),[\d\.\-]+)
filename_x86		 = $(NVIDIA_FILENAME_X86)
filename_x86_64		 = $(NVIDIA_FILENAME_X86_64)
dirname_x86		 = $(NVIDIA_DIRNAME_X86)
dirname_x86_64		 = $(NVIDIA_DIRNAME_X86_64)

# system libdir
libdir			 = usr/lib$(if $(MULTIARCH),/$(DEB_HOST_MULTIARCH))
# nvidia specific directory below $(libdir)
nvidia_private		 = nvidia$(if $(legacy),/$(patsubst -%,%,$(legacy)),/current)

CONTROL_PREFIXES = nvidia-glx libgl1-nvidia nvidia-kernel nvidia-alternative xserver-xorg-video-nvidia
ALL_CONTROL	:= $(wildcard $(patsubst %,debian/%*,$(CONTROL_PREFIXES)))
LEGACY_CONTROL	:= $(wildcard $(patsubst %,debian/%$(legacy)*,$(CONTROL_PREFIXES)))
RENAME_CONTROL	 = $(filter-out $(LEGACY_CONTROL),$(ALL_CONTROL))
RENAMED_CONTROL	 = $(patsubst debian/nvidia-glx%,debian/nvidia-glx$(legacy)%,\
			$(patsubst debian/libgl1-nvidia%,debian/libgl1-nvidia$(legacy)%,\
			$(patsubst debian/nvidia-kernel%,debian/nvidia-kernel$(legacy)%,\
			$(patsubst debian/nvidia-alternative%,debian/nvidia-alternative$(legacy)%,\
			$(patsubst debian/xserver-xorg-video-nvidia%,debian/xserver-xorg-video-nvidia$(legacy)%,\
				$(RENAME_CONTROL))))))
TEMPLATES	:= $(wildcard debian/*.in debian/module/debian/*.in debian/detect/*.in)
AUTOGEN		+= $(patsubst %.in,%,$(TEMPLATES))
AUTOGEN		+= debian/module/debian/changelog
AUTOGEN		+= $(patsubst %.in,%,$(RENAMED_CONTROL))
AUTOKEEP	 = debian/watch
AUTOCLEAN	 = $(filter-out $(AUTOKEEP),$(AUTOGEN))

module_source	 = debian/nvidia-kernel$(legacy)-source/usr/src/modules/nvidia-kernel$(legacy)
module_tbz	 = $(subst /modules/,/,$(module_source)).tar.bz2
dkms_source	 = debian/nvidia-kernel$(legacy)-dkms/usr/src/nvidia-$(version)

comma		 = ,
xorg_depends	 = $(foreach abi, $(XORG_ABI_LIST), xorg-video-abi-$(abi) |)
xorg_depends	+= $(if $(BACKPORT), xserver-xorg-core (<< 2:1.7.7) |)
xorg_depends	+= $(comma) xserver-xorg-core $(XORG_BOUND)
xorg_provides	 = xorg-driver-video
xorg_provides	+= $(if $(filter-out squeeze,$(BACKPORT)), $(comma) xserver-xorg-video-6)

# sanity checks
$(if $(and $(BACKPORT),$(MULTIARCH)),$(error Oops, backports do not support multiarch.))


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


unpack-stamp: ${filename_x86} ${filename_x86_64}
	dh_testdir
	# extract both so we can fetch the kernel object code for both arches
	sh ${filename_x86} --extract-only
	sh ${filename_x86_64} --extract-only
	ln -s ${dirname_x86} NVIDIA-Linux-i386
	ln -s ${dirname_x86_64} NVIDIA-Linux-amd64
	ln -s NVIDIA-Linux-$(DEB_HOST_ARCH) NVIDIA-Linux
	test -f NVIDIA-Linux-i386/README.txt || \
		mv NVIDIA-Linux-i386/usr/share/doc/README.txt NVIDIA-Linux-i386/README.txt 2>/dev/null || \
		mv NVIDIA-Linux-i386/usr/share/doc/README NVIDIA-Linux-i386/README.txt
	test -f NVIDIA-Linux-amd64/README.txt || \
		mv NVIDIA-Linux-amd64/usr/share/doc/README.txt NVIDIA-Linux-amd64/README.txt 2>/dev/null || \
		mv NVIDIA-Linux-amd64/usr/share/doc/README NVIDIA-Linux-amd64/README.txt
	test -f NVIDIA-Linux-amd64/NVIDIA_Changelog || \
		mv NVIDIA-Linux-amd64/usr/share/doc/NVIDIA_Changelog NVIDIA-Linux-amd64/
	test -d NVIDIA-Linux-i386/kernel || \
		mv NVIDIA-Linux-i386/usr/src/nv NVIDIA-Linux-i386/kernel
	test -d NVIDIA-Linux-amd64/kernel || \
		mv NVIDIA-Linux-amd64/usr/src/nv NVIDIA-Linux-amd64/kernel
	ls -al
	touch $@

nv-kernel.ids: unpack-stamp
	sh debian/extract-pci-ids.sh NVIDIA-Linux/kernel/nv-kernel.o \
		| tr a-f A-F | sort -u > $@
	test -s $@ || cp debian/$@ $@
	@set -e -x ; \
	if ! cmp -s debian/$@ $@ ; then \
		diff -u debian/$@ $@ || true ; \
		: "*** Supported PCI IDs have changed. See diff above. Aborting. ***"; \
		exit 1 ; \
	fi

nv-readme.ids: unpack-stamp
	sed	-e '0,/A. Supported\|APPENDIX A: SUPPORTED/d' \
		-e '0,/Appendix A. Supported\|APPENDIX A: SUPPORTED/d' \
		-e '0,/^Below\|APPENDIX B/{/ 0x/s/.*  0x\([0-9a-fA-F]\{4\}\).*/10de\1/p};d' \
		NVIDIA-Linux/README.txt \
		| tr a-f A-F | sort -u > $@
	@set -e -x ; \
	if ! cmp -s debian/$@ $@ ; then \
		diff -u debian/$@ $@ || true ; \
		: "*** Supported PCI IDs have changed. See diff above. Aborting. ***"; \
		exit 1 ; \
	fi

nvidia.ids: nv-readme.ids
	cp $< $@

# 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


.PHONY: binary binary-arch binary-indep build clean install
binary binary-arch binary-indep build clean install:
	dh $@ --with dkms

override_dh_auto_clean:
	rm -f NVIDIA-Linux-i386 NVIDIA-Linux-amd64 NVIDIA-Linux
	rm -fr $(dirname_x86) $(dirname_x86_64)
	rm -fr debian/temp
	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

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

override_dh_auto_configure: prepare

# Build two kernel module source tarballs for use with
#  - module-assistant and make-kpkg
#  - dkms
.PHONY: install-into-tmp build-kernel-source-tree build-kernel-dkms-tree kernel-source-tree
override_dh_auto_install: install-into-tmp build-kernel-source-tree build-kernel-dkms-tree

install-into-tmp:
	# "Install" into debian/tmp.
	cp -al NVIDIA-Linux/ debian/tmp
	rm -f debian/tmp/NVIDIA_Changelog
	cp -al NVIDIA-Linux-amd64/NVIDIA_Changelog debian/tmp/

	# Create xorg.conf.sample
	test ! -f debian/tmp/usr/share/doc/XF86Config.sample || \
	sed \
	    -e 's/XF86Config(4\/5)/xorg.conf(5)/g' \
	    -e 's/XF86Config/xorg.conf/g' \
	    -e 's/XFree86/Xorg/g' \
	    < debian/tmp/usr/share/doc/XF86Config.sample \
	    > debian/tmp/usr/share/doc/xorg.conf.sample

build-kernel-source-tree: install-into-tmp
	# Build the nvidia-kernel-source tree.
	mkdir -p $(module_source)
	mv debian/tmp/kernel/* $(module_source)/
	# This copy of the changelog is going to be installed into the module
	# binary packages.
	cp -a debian/tmp/NVIDIA_Changelog $(module_source)/

	# We don't want these makefiles that don't work with kbuild.
	rm $(module_source)/makefile
	rm $(module_source)/Makefile.nvidia

	# We want both 32 and 64 bit versions of nv-kernel.o.  Do not use a
	# name matching *.o to prevent accidental deletion by some clean
	# target.
	cp -a NVIDIA-Linux-i386/kernel/nv-kernel.o \
	    $(module_source)/nv-kernel.o.i386
	cp -a NVIDIA-Linux-amd64/kernel/nv-kernel.o \
	    $(module_source)/nv-kernel.o.x86_64
	rm -f $(module_source)/nv-kernel.o

	# Install a debian/ tree and new conftest files that work purely
	# with kbuild and don't require root into the module package.
	cp -a debian/module/* $(module_source)/
	cp -a debian/copyright $(module_source)/debian/
	cp -a debian/bug-script $(module_source)/debian/
	cp -a debian/bug-control $(module_source)/debian/
	echo "Submit-As: nvidia-kernel$(legacy)-source" >> $(module_source)/debian/bug-control

	# Fix permissions.
	chmod -R a-sx,u=rwX,go=rX $(module_source)/../..
	chmod a+x $(module_source)/debian/rules
	chmod a+x $(module_source)/conftest.sh

	# Build the tarball.
	tar cfj $(module_tbz) \
	    --owner=root --group=src -C $(module_source)/../.. \
	    --exclude '*.in' --exclude '.svn' modules
	tar tfvj $(module_tbz)

build-kernel-dkms-tree: build-kernel-source-tree
	# Use the nvidia-kernel-source source to create the DKMS tree.
	mkdir -p $(dir $(dkms_source))
	mv $(module_source) $(dkms_source)
	rmdir $(dir $(module_source))
	cd $(dkms_source) \
	    && QUILT_PATCHES=debian/patches quilt --quiltrc /dev/null push -a || test $$? = 2 \
	    && rm -rf .pc debian
	ls -la $(dkms_source)

# This target is not used by the package build process.  You can use it if
# you want to work with the patches that get applied to the module source.
kernel-source-tree: prepare build-kernel-source-tree
	rm -rf $@
	cp -a $(module_source) $@
	cd $@ && QUILT_PATCHES=../debian/module/debian/patches quilt --quiltrc /dev/null push -a || test $$? = 2

override_dh_install:
	dh_install --list-missing

override_dh_installchangelogs:
	dh_installchangelogs debian/tmp/NVIDIA_Changelog

override_dh_dkms:
	dh_dkms -V $(version)

override_dh_bugfiles:
	dh_bugfiles -A

override_dh_makeshlibs:
	dh_makeshlibs -Xvdpau/libvdpau_nvidia.so -Xtls/libnvidia-tls.so
	# Redirect shlibs for libGL.so.1 to libgl1-mesa-glx | libgl1.
	test ! -f debian/libgl1-nvidia$(legacy)-glx/DEBIAN/shlibs || \
		sed -i -e '/^libGL 1 /s/.*/libGL 1 libgl1-mesa-glx | libgl1/' debian/libgl1-nvidia$(legacy)-glx/DEBIAN/shlibs
	# Remove libGL.so from symbols files in order not to override our special shlibs files.
	test ! -f debian/libgl1-nvidia$(legacy)-glx/DEBIAN/symbols || \
		sed -i -e '/^libGL\.so/,/^lib/{/^libGL\.so\|^ /d}' debian/libgl1-nvidia$(legacy)-glx/DEBIAN/symbols

override_dh_shlibdeps:
	LD_LIBRARY_PATH=/$(libdir)/$(nvidia_private):$(LD_LIBRARY_PATH) dh_shlibdeps

override_dh_gencontrol:
	dh_gencontrol -- -V'nvidia:Version=$(version)' \
		-V'nvidia:xorgDepends=$(xorg_depends)' \
		-V'nvidia:xorgProvides=$(xorg_provides)' \
		-V'nvidia:Legacy=$(legacy)' \
		-V'nvidia:LegacyDesc=$(legacy_description)' \
		-V'nvidia:Perfkit=$(perfkit)' \
		-V'nvidia-settings=$(NVIDIA_SETTINGS)' \
		-Vnvidia:Models="`cat debian/control.models`"

# 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_builddeb:
	dh_builddeb -- -Zxz

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

# Generating control files
%:: %.in debian/rules debian/rules.defs
	perl -p \
	-e 's{#VERSION#}{$(version)}g;' \
	-e 's{#MAJOR#}{$(firstword $(subst ., ,$(version)))}g;' \
	-e 's{#LEGACY#}{$(legacy)}g;' \
	-e 's{#WATCH_PATTERN#}{$(subst \,\\,$(watch_pattern))}g;' \
	-e 's{#LIBDIR#}{$(libdir)}g;' \
	-e 's{#PRIVATE#}{$(nvidia_private)}g;' \
	< $< > $@

debian/module/debian/changelog: debian/changelog
	sed '1s/^nvidia-graphics-drivers/nvidia-kernel/g' $< > $@


# Renaming control files for legacy packaging
define rename-template
$1$$(legacy)%: $1%
	cp -a $$< $$@
endef
ifneq (,$(legacy))
$(foreach p,$(CONTROL_PREFIXES),$(eval $(call rename-template,$p)))
endif

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

# only invoked manually
%.txt: %.list
	cat $< \
	| sed -e 's/^10DE.... *//; /^$$/d' \
	| uniq \
	| sed -e 's/ /#/g; s/#*$$/,/; $$ s/,$$/./' \
	| ( tr '\n' ' '; echo ) \
	| fold -s -w 78 \
	| sed -e 's/#/ /g; s/ *$$//' > $@

# only invoked manually
pci.ids.nvidia: /usr/share/misc/pci.ids
	sed -nr '/^10de/,/^10df/ { /^\t\t/d; /\t/ { s/  (.*) \[(.*)\]$$/  \2 [\1]/; s/^\t/10de/; p} }' $< > $@.tmp
	cut -c 1-8 $@.tmp | tr a-f A-F > $@.tmp1
	cut -c 9- $@.tmp | paste -d '' $@.tmp1 - > $@
	$(RM) $@.tmp $@.tmp1

# only invoked manually
%.names: %.ids pci.ids.nvidia
	cat $< | \
	while read id ; do \
		grep ^$$id pci.ids.nvidia || echo $$id ; \
	done > $@

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

prepare-squeeze-backport:
	echo 8 > debian/compat
	sed -i 	-e '/^MULTIARCH/ s/^/#/; s/yes/no/' \
		-e '/^#BACKPORT/ s/^#//' \
		debian/rules.defs
	sed -i -e 's/debhelper (>= .*)/debhelper (>= 8)/' \
	       -e '/^Multi-Arch:/ d' \
	       -e 's/0.4.1-3/0.4/' \
	       debian/control
	sed -i -e '/^package-contains-empty-directory usr\/lib\/tls\// s/^/#/' \
		debian/libgl1-nvidia-glx.lintian-overrides.in
	debchange --bpo "Disable multiarch build."
	debchange -a "Reduce Build-Depends: debhelper and compat level to 8."
	debchange -a "Note: Please report bugs found in this backported package to the Debian BTS, not the backports mailing list."

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

PASV	?= --pasv

.PHONY: get-orig-source
get-orig-source:
	rm -rf get-orig-source || true
	mkdir get-orig-source
	ln -v ../.cache/*-$(version).run get-orig-source/ 2>/dev/null || true
	ln -v ../.cache/*-$(version)-*.run get-orig-source/ 2>/dev/null || true
	uscan --no-symlink --download-current-version $(PASV) \
	    --watchfile debian/watch --destdir get-orig-source
	test $$(ls get-orig-source/* | wc -l) = 2  # we need exactly 2 downloaded files
	@set -e -x ; \
	    cd get-orig-source ; \
	    newversion=$$(ls *-x86-*.run | sed -e 's/.*-\([0-9.]*\)\(-.*\)\?\.run/\1/') ; \
	    mkdir nvidia-graphics-drivers-$${newversion}.orig ; \
	    mv *.run nvidia-graphics-drivers-$${newversion}.orig/ ; \
	    chmod 0755 nvidia-graphics-drivers-$${newversion}.orig/* ; \
	    tar cfvz ../nvidia-graphics-drivers$(legacy)_$$newversion.orig.tar.gz \
		--owner=root --group=src \
		nvidia-graphics-drivers-$${newversion}.orig
	rm -rf get-orig-source
