#!/bin/sh

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

postinst_found=0

case "$1" in
    configure)
	[ ! -e /usr/bin/install-saa716x.sh ] || mv -f /usr/bin/install-saa716x.sh /usr/bin/install-saa716x
	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 -le 19 ]; 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

	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."
			if $DKMS_POSTINST $DKMS_NAME $DKMS_VERSION /usr/share/$DKMS_NAME-dkms "" $2; then
				echo
				echo "You can install the newest version with 'install-saa716x'"
				echo "---------------------------------------------------------"
			fi
			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
