#!/bin/sh
# Copyright (C) 2002-2005 Flavio Stanchina
# Copyright (C) 2005-2006 Aric Cyr
# Copyright (C) 2007 Mario Limonciello
# Copyright (C) 2009 Alberto Milone

set -e

NAME=MODULE_NAME
PACKAGE_NAME=$NAME-dkms
DEB_NAME=$(echo $PACKAGE_NAME | sed 's,_,-,')
CVERSION=`dpkg-query -W -f='${Version}' $DEB_NAME | awk -F "-" '{print $1}' | cut -d\: -f2`
ARCH=`dpkg --print-architecture`

dkms_configure () {
	for POSTINST in /usr/lib/dkms/common.postinst "/usr/share/$PACKAGE_NAME/postinst"; do
		if [ -f "$POSTINST" ]; then
			"$POSTINST" "$NAME" "$CVERSION" "/usr/share/$PACKAGE_NAME" "$ARCH" "$2"
			return $?
		fi
		echo "WARNING: $POSTINST does not exist." >&2
	done
	echo "ERROR: DKMS version is too old and $PACKAGE_NAME was not" >&2
	echo "built with legacy DKMS support." >&2
	echo "You must either rebuild $PACKAGE_NAME with legacy postinst" >&2
	echo "support or upgrade DKMS to a more current version." >&2
	return 1
}

service_restart () {
	if hash deb-systemd-invoke 2>/dev/null; then
		deb-systemd-invoke enable pf_ring > /dev/null
		deb-systemd-invoke restart pf_ring || echo "Failure restarting pf_ring"
		deb-systemd-invoke restart cluster || echo "Failure restarting cluster"
	elif hash systemctl 2>/dev/null; then    
		systemctl enable pf_ring > /dev/null
		systemctl restart pf_ring || echo "Failure restarting pf_ring"
		systemctl restart cluster || echo "Failure restarting cluster"
	else
		update-rc.d pf_ring defaults 30 >/dev/null
		update-rc.d cluster defaults 40 >/dev/null
		/etc/init.d/pf_ring restart || echo "Failure restarting pf_ring"
		/etc/init.d/cluster restart || echo "Failure restarting cluster"
	fi
}

case "$1" in
	configure)
		CMDLINE=$(tr -d '\0' < /proc/1/cmdline)
		if [ ! -z "${CMDLINE##*system*}" ] && [ ! -z "${CMDLINE##*init*}" ]; then
			exit 0 # no init/systemd (in a container)
		fi

		dkms_configure
		service_restart
	;;

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

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
