#!/bin/sh -e

case "$1" in
    configure)
	# continue below
    ;;

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

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

umask 022

if ! grep -q ntopng /etc/group; then
    echo 'Creating ntopng group'
    /usr/sbin/groupadd -r ntopng
fi

if ! /usr/bin/id -u ntopng > /dev/null 2>&1; then 
    echo "Creating ntopng user..."
    /usr/sbin/useradd -M -N -g ntopng -r ntopng
fi

DATA_DIR=/var/lib/ntopng
if [ ! -d "$DATA_DIR" ]; then
    mkdir $DATA_DIR
    /bin/chown ntopng:ntopng $DATA_DIR
    /bin/chmod 700 $DATA_DIR
fi

echo "Rebuilding ld cache..."
/sbin/ldconfig

if [ ! -f /usr/local/bin/ntopng ] && [ ! -L /usr/local/bin/ntopng ] ; then
    ln -s /usr/bin/ntopng /usr/local/bin/ntopng
fi

if [ -d /usr/local/share/ntopng ] ; then
    mv /usr/local/share/ntopng /usr/local/share/ntopng.disabled
fi

if [ -f /.dockerenv ]; then exit 0; fi

# Start service after upgrade/install
echo "(Re)Starting ntopng..."
if hash systemctl 2>/dev/null; then
    systemctl daemon-reload
    systemctl reset-failed
    systemctl enable ntopng
    systemctl restart ntopng
elif [ -f /etc/init.d/ntopng ]; then
    update-rc.d ntopng defaults 93 >/dev/null
    /etc/init.d/ntopng restart
fi

exit 0
