#!/bin/sh

set -e

default=/etc/default/ngcp-rtpengine-daemon
modname=xt_RTPENGINE

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 kernel module check"
else
	if [ -f $default ]; then
		. $default || true
	fi

	if [ -n "$TABLE" ] && [ "$TABLE" -ge 0 ] && \
		 [ -n "$NO_FALLBACK" ] && \
		 { [ "$NO_FALLBACK" = "1" ] || [ "$NO_FALLBACK" = "yes" ] ; }
	then
		if lsmod | grep -q $modname || modinfo $modname > /dev/null 2> /dev/null; then
			true
		else
			echo "Kernel module $modname not found and NO_FALLBACK is set."
			echo "Daemon restart not performed."
			exit 0
		fi
	fi
fi

if [ "$1" = configure ]; then
	adduser --system --home /nonexistent --gecos rtpengine \
		--no-create-home --disabled-password \
		--group --quiet rtpengine || true

	rtpdir='/var/spool/rtpengine'
	if ! dpkg-statoverride --list "$rtpdir" > /dev/null 2>&1; then
		chown rtpengine:rtpengine "$rtpdir"
		chmod 0770 "$rtpdir"
	fi

	cachedir='/var/cache/rtpengine'
	if ! dpkg-statoverride --list "$cachedir" > /dev/null 2>&1; then
		chown rtpengine:rtpengine "$cachedir"
		chmod 0770 "$cachedir"
	fi

	# set up modprobe.d fragment for auto-load usage
	if ! [ -f /etc/modprobe.d/rtpengine.conf ] || grep -q DPKG-GENERATED /etc/modprobe.d/rtpengine.conf; then
		OPTIONS="options xt_RTPENGINE proc_mask=0x7"

		PUID=$(id -u rtpengine 2> /dev/null)
		test -z "$PUID" || OPTIONS="$OPTIONS proc_uid=$PUID"
		PGID=$(id -g rtpengine 2> /dev/null)
		test -z "$PGID" || OPTIONS="$OPTIONS proc_gid=$PGID"

		( echo "# DPKG-GENERATED FILE";
		  echo "$OPTIONS" ) > /etc/modprobe.d/rtpengine.conf
	fi
fi

#DEBHELPER#

exit 0

