#!/bin/sh

set -e

package=rtpengine-kernel-dkms
name=rtpengine

version=$(dpkg-query -W -f="\${Version}" "$package" \
		|rev|cut -d- -f2-|rev|cut -d':' -f2|tr -d "\n")


if [ -x "$(which ngcp-virt-identify)" ]; then
	if ngcp-virt-identify --type container; then
		VIRT="yes"
	fi
fi

if [ "$VIRT" = "yes" ]; then
	echo "Container environment detected. Skip dkms"
else
	isadded=$(dkms status -m "$name" -v "$version")
	if [ -z "${isadded}" ] ; then
		dkms add -m "$name" -v "$version"
	fi

	if [ "$1" = 'configure' ] ; then
                KERNELS=$(ls /lib/modules/ 2>/dev/null || true)
                for kernel in $KERNELS; do
                        if [ ! -r "/lib/modules/$kernel/build" ]; then
                                # cannot build modules for this kernel
                                continue
                        fi
		        ( dkms build -m "$name" -v "$version" -k "$kernel" && dkms install -m "$name" -v "$version" -k "$kernel" ) || true
                done

		# try to start the daemon
		if [ -x /etc/init.d/rtpengine-daemon ] ; then
			invoke-rc.d rtpengine-daemon restart || true
		fi
	fi
fi

#DEBHELPER#

exit 0

