#!/usr/bin/make -f

# See debhelper(7) (uncomment to enable).
# Output every command that modifies files on the build system.

DRIVER_NAME := ntfs3
VERSION := $(shell dpkg-parsechangelog | grep '^Version:' | cut -d' ' -f2 | cut -d- -f1 | cut -d\: -f2)
PKG_NAME := ntfs3
PKG_kernel_src  := $(PKG_NAME)-dkms
ARCH := $(shell dpkg --print-architecture)
#ifeq ($(ARCH),amd64)
#ARCH_SUFFIX=x86_64
#else
#ARCH_SUFFIX=i386
#endif

KVER_MIN := $(shell ls -1 $(DRIVER_NAME) | grep "^[0-9]\." | sort -V | head -1)
KVER_MAX := $(shell ls -1 $(DRIVER_NAME) | grep "^[0-9]\." | sort -V | tail -1)

## We need one version lower for BUILD_EXCLUSIVE_KERNEL_MIN
## and one version higher for BUILD_EXCLUSIVE_KERNEL_MAX
KVER_MIN_MAJOR := $(shell echo $(KVER_MIN) | sed "s/\([0-9]\+\)\.[0-9]\+/\1/g")
KVER_MIN_MINOR := $(shell echo $(KVER_MIN) | sed "s/[0-9]\+\.\([0-9]\+\)/\1/g")

KVER_MAX_MAJOR := $(shell echo $(KVER_MAX) | sed "s/\([0-9]\+\)\.[0-9]\+/\1/g")
KVER_MAX_MINOR := $(shell echo $(KVER_MAX) | sed "s/[0-9]\+\.\([0-9]\+\)/\1/g")

MOD_KVER_MIN_MINOR := $(shell echo $$(($(KVER_MIN_MINOR)-1)))
MOD_KVER_MAX_MINOR := $(shell echo $$(($(KVER_MAX_MINOR)+1)))

#export DH_VERBOSE = 1


# See FEATURE AREAS in dpkg-buildflags(1).
#export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# See ENVIRONMENT in dpkg-buildflags(1).
# Package maintainers to append CFLAGS.
#export DEB_CFLAGS_MAINT_APPEND  = -Wall -pedantic
# Package maintainers to append LDFLAGS.
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed


%:
	dh $@


# dh_make generated override targets.
# This is an example for Cmake (see <https://bugs.debian.org/641051>).
#override_dh_auto_configure:
#	dh_auto_configure -- \
#	-DCMAKE_LIBRARY_PATH=$(DEB_HOST_MULTIARCH)

# we don't actually build/clean the source here, it's dkms
override_dh_auto_clean:

override_dh_auto_build:

override_dh_auto_install:
	# just create .install files from templates.
	for i in dkms.conf \
		$(PKG_kernel_src).install \
		$(PKG_kernel_src).postinst \
		$(PKG_kernel_src).prerm; do \
			sed \
			-e "s|#PKG_NAME#|$(PKG_NAME)|" \
			-e "s|#DRIVER_NAME#|$(DRIVER_NAME)|" \
			-e "s|#VERSION#|$(VERSION)|" \
			-e "s|#ARCH#|$(ARCH_SUFFIX)|" \
			-e "s|#MOD_MIN_VER#|$(KVER_MAX_MAJOR).$(KVER_MIN_MINOR)|" \
			-e "s|#MOD_MAX_VER#|$(KVER_MAX_MAJOR).$(KVER_MAX_MINOR)|" \
			-e "s|#MIN_VER#|$(KVER_MAX_MAJOR).$(MOD_KVER_MIN_MINOR)|" \
			-e "s|#MAX_VER#|$(KVER_MAX_MAJOR).$(MOD_KVER_MAX_MINOR)|" \
			debian/$$i.in > debian/$$i; \
	done

override_dh_clean:
	dh_clean

	for i in dkms.conf \
		$(PKG_kernel_src).install \
		$(PKG_kernel_src).postinst \
		$(PKG_kernel_src).prerm \
		$(PKG_kernel_src); do \
			rm -f debian/$$i; \
	done