#!/bin/sh
# $Id: postinst,v 1.7 2003/09/08 18:09:03 agx Exp $

set -e

VARDIR="/var/lib/portsentry"

# Source debconf library.
. /usr/share/debconf/confmodule

get_services() {
    services=
    if [ -n "$TCP_MODE" ]; then
        services="portsentry@$TCP_MODE.service"
    fi
    if [ -n "$UDP_MODE" ]; then
        services="$services portsentry@$UDP_MODE.service"
    fi
}

PS_DEFAULT="/etc/default/portsentry"
if [ "$1" = "configure" ] && ! [ -e "$PS_DEFAULT" ]; then
    # create /e/d/portsentry if it doesn't exist on first time installs
    TCP_MODE=tcp
    UDP_MODE=udp
    get_services
    cat >$PS_DEFAULT <<EOF
# $PS_DEFAULT
#
# This file is read by /etc/init.d/portsentry. See the portsentry.8
# manpage for details.
#
# The options in this file refer to commandline arguments (all in lowercase)
# of portsentry. Use only one tcp and udp mode at a time.
#
# This file is not used by the systemd units — $services.
#
TCP_MODE="$TCP_MODE"
UDP_MODE="$UDP_MODE"
EOF
    chown root:root $PS_DEFAULT
    chmod 644 $PS_DEFAULT
fi
if [ "$1" = "configure" ] ; then
    # Addressing bug #1010718 (After installed portsentry doesn't create automatically portsentry.history)
    if [ ! -d ${VARDIR} ] ; then
      mkdir -p ${VARDIR}
    fi
    touch ${VARDIR}/portsentry.history
fi
if [ -z "$services" ] && { [ -n "$2" ] && dpkg --compare-versions "$2" lt 1.2-15; }; then
    . "$PS_DEFAULT"
    get_services
fi
if [ -n "$services" ] && { [ -n "$2" ] && dpkg --compare-versions "$2" lt 1.2-15; }; then
    # Can't do deb-systemd-helper enable $services due to Bug#801822
    for s in $services; do
        ln -vs "/lib/systemd/system/portsentry@.service" "/etc/systemd/system/multi-user.target.wants/$s"
    done
    [ -d "/run/systemd/system" ] && systemctl daemon-reload
    deb-systemd-invoke start $services
fi

# this is not a very nice way to do things, but it's the safest one
if [ -d "/run/systemd/system" ]; then
    systemctl restart "portsentry@*.service"
elif [ "`pidof /usr/sbin/portsentry`" ]; then
    echo -n "Stopping anti portscan daemon: "
    kill `pidof /usr/sbin/portsentry`
    echo "portsentry."
fi

# until portsentry is fixed:
db_stop

#DEBHELPER#
