#!/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 n2n /etc/group; then
    echo 'Creating n2n group'
    /usr/sbin/groupadd -r n2n
fi

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

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

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

# Start service after upgrade/install
systemctl daemon-reload
systemctl reset-failed

# Enable edge
if systemctl -q is-active edge; then
    # only restart edge if it's already running
    echo "Restarting n2n edge..."
    deb-systemd-invoke restart edge
fi

# Restart specific services if already running
deb-systemd-invoke restart 'edge@*.service' 'edge-ntopng@*.service'

# Enable supernode
if systemctl -q is-active supernode; then
    # only restart supernode if it's already running
    echo "Restarting n2n supernode..."
    deb-systemd-invoke restart supernode
fi

exit 0
