#!/bin/sh -e

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

action="$1"
oldversion="$2"

if [ "$action" != configure ]
  then
  exit 0
fi

clean_conf() {
  [ -f $1 ] || return
  awk '
    BEGIN { orig=1 }
    /^#begin: sagator/ { orig=0; next }
    /^#end: sagator/ { orig=1; next }
    orig==1 { print }
  ' $1 > $1.temp
  mv -f $1.temp $1
}

# starting of daemon
update-rc.d sagator defaults

# fix permissions
chgrp vscan /etc/sagator.conf /usr/share/sagator/etc
chown -Rh vscan:vscan /var/log/sagator /var/www/html/sagator

# update configuration
/usr/share/sagator/updatecfg.py >&2 || true

if db_get sagator/mkchroot; then
        # make chroot
        eval `grep ^CHROOT= /etc/sagator.conf`
        if [ "$CHROOT" ]; then
                /usr/sbin/mkchroot.sagator --auto --quiet
                if db_get sagator/updateclamav; then
                        freshclam --datadir $CHROOT/var/lib/clamav \
                          || true
                fi
        fi >&2
fi
if db_get sagator/confpostfix; then
        if [ "$RET" = "true" ]; then
	        if [ -f /etc/postfix/master.cf -a -f /etc/postfix/main.cf ]; then
                        db_subst sagator/confpostfix boolean false
                        db_go
                        echo -n "Configuring postfix ... "
                        clean_conf /etc/postfix/master.cf
                        clean_conf /etc/postfix/main.cf
                        /bin/sh /usr/share/doc/sagator/configure_postfix.sh
                        echo "done"
                fi >&2
        fi
fi

echo "Please restart sagator manually."
exit 0 # exit before debhelper restarts sagator

if [ -x "/etc/init.d/sagator" ]; then
        update-rc.d sagator defaults >/dev/null
        if [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
                invoke-rc.d sagator start >&2 || exit $?
        else
                /etc/init.d/sagator start >&2 || exit $?
        fi
fi

#DEBHELPER#
