#!/bin/sh

DKMS_NAME=saa716x
DKMS_VERSION=1.0
SOURCE=/usr/src/$DKMS_NAME-$DKMS_VERSION
PATCH=$SOURCE/saa716x.diff
KMAJOR=$(uname -r | cut -d'.' -f1)
KMINOR=$(uname -r | cut -d'.' -f2)

postinst_found=0

case "$1" in
    configure)
	if [ $KMAJOR -lt 4 ]; then
	    echo "ERROR: Only kernel version 4.12 or higher is supported!"
	    exit 1
	fi
	if [ $KMAJOR -eq 4 ] && [ $KMINOR -lt 12 ]; then
	    echo "ERROR: Only kernel version 4.12 or higher is supported!"
	    exit 1
	fi
	if [ $KMAJOR -eq 4 ] && [ $KMINOR -lt 20 ]; then
	    sed -i "s/drivers\/media\/pci/drivers\/media\/common/g" $SOURCE/dkms.conf
	else
	    sed -i "s/drivers\/media\/common/drivers\/media\/pci/g" $SOURCE/dkms.conf
	fi
	chmod a+x $SOURCE/make.sh

	rm -f $PATCH
	if [ $KMAJOR -lt 6 ]; then
	    ln -s $SOURCE/patches/saa716x-1.diff $PATCH
	else
	    [ $KMAJOR -eq 6 ] && [ $KMINOR -lt 15 ] && ln -s $SOURCE/patches/saa716x-1.diff $PATCH
	fi
	[ -e $PATCH ] || ln -s $SOURCE/patches/saa716x-2.diff $PATCH

	for DKMS_POSTINST in /usr/lib/dkms/common.postinst /usr/share/$DKMS_NAME-dkms/postinst; do
		if [ -f $DKMS_POSTINST ]; then
			echo "That takes a while... be patient."
			$DKMS_POSTINST $DKMS_NAME $DKMS_VERSION /usr/share/$DKMS_NAME-dkms "" $2
			postinst_found=1
			break
		fi
	done
	if [ "$postinst_found" -eq 0 ]; then
		echo "ERROR: DKMS version is too old and $DKMS_NAME-dkms was not"
		echo "built with legacy DKMS support."
		echo "You must either rebuild $DKMS_NAME-dkms with legacy postinst"
		echo "support or upgrade DKMS to a more current version."
		exit 1
	fi
	;;

    abort-upgrade|abort-remove|abort-deconfigure)
	;;

    *)
	echo "postinst called with unknown argument '$1'" >&2
	exit 1
    ;;
esac

exit 0
