#!/bin/sh -e

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
}

conf_postfix() {
clean_conf /etc/postfix/master.cf
clean_conf /etc/postfix/main.cf
cat >> /etc/postfix/main.cf << EOF
#begin: sagator
content_filter=smtp:[127.0.0.1]:27
#end: sagator
EOF
cat >> /etc/postfix/master.cf << EOF
#begin: sagator
127.0.0.1:26    inet n - n - 30 smtpd
  -o content_filter=
  -o myhostname=sagator.`hostname`
  -o local_recipient_maps=  -o relay_recipient_maps=
  -o mynetworks=127.0.0.0/8  -o mynetworks_style=host
  -o smtpd_restriction_classes=  -o smtpd_client_restrictions=
  -o smtpd_helo_restrictions=  -o smtpd_sender_restrictions=
  -o smtpd_recipient_restrictions=permit_mynetworks,reject
  -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks
#end: sagator
EOF
}

case "$1" in
  configure)
	# Source debconf library.
	. /usr/share/debconf/confmodule

	# starting of daemon
	update-rc.d sagator defaults

        # fix permissions
        chgrp vscan /etc/sagator.conf /usr/lib/sagator/config

	# update configuration
	/usr/lib/sagator/updatecfg.py || 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
	fi
	if db_get sagator/confpostfix; then
		if [ -f /etc/postfix/master.cf -a -f /etc/postfix/main.cf ]; then
			if [ "$RET" = "true" ]; then
				db_subst sagator/confpostfix boolean false
				db_go
				echo -n "Configuring postfix ... "
				conf_postfix
				echo "done"
			else
				clean_conf /etc/postfix/master.cf
				clean_conf /etc/postfix/main.cf
			fi
		fi
	fi
	
	# restart sagator
	#/etc/init.d/sagator restart
    ;;
  abort-remove|abort-deconfigure|abort-upgrade)
    ;;
  *)
    echo "postinst called with unknown argument \`$1'" >&2
    exit 1
    ;;
esac
                                                                                
exit 0
