#! /bin/sh
# postinst script for smtp-gated
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
#
# quoting from the policy:
#     Any necessary prompting should almost always be confined to the
#     post-installation script, and should be protected with a conditional
#     so that unnecessary prompting doesn't happen if a package's
#     installation fails and the `postinst' is called with `abort-upgrade',
#     `abort-remove' or `abort-deconfigure'.

NAME=smtp-gated
USERNAME=smtpgw
PROG=/usr/sbin/$NAME

[ -f /etc/defaults/$NAME ] && . /etc/defaults/$NAME
CONF=/etc/$NAME.conf


new_config()
{
	[ -e "$CONF" ] && return 0
#	[ ! -w "$CONF" ] && echo "No write permission to $CONF" && return 1

	$PROG -t | head --lines=1 >>"$CONF"
	echo "# You can list all options by running: smtp-gated -T [config_file]" >>"$CONF"
	cat >>"$CONF" <<_EOF_

proxy_name isp.example.com
abuse abuse@isp.example.com
bind_address 127.0.0.1
mode netfilter
set_user $USERNAME
; max_connections 64
; max_per_host 8
antivirus_type off
antivirus_path /var/run/clamav/clamd.ctl
antispam_type off
antispam_path /var/run/spamd/spamd_socket
_EOF_
}

upgrade_config()
{
	cp "$CONF" "$CONF".pre-upgrade
#	sed -e 's/dumpfile/statefile' <"$CONF" >"$CONF".tmp
#	chmod --reference="$CONF" "$CONF".tmp
#	chown --reference="$CONF" "$CONF".tmp
#	mv "$CONF".tmp "$CONF"
}

case "$1" in
	configure)
		mkdir -p /var/spool/$NAME/{msg,lock}
		chown -R $USERNAME:$USERNAME /var/spool/$NAME
		chmod -R 750 /var/spool/$NAME
		chown $USERNAME:$USERNAME /var/run/$NAME
		update-rc.d $NAME defaults >/dev/null

		if [ ! -f "$CONF" ]; then
			new_config
		else
			upgrade_config
		fi

		echo "Checking configuration file for errors..."
		$PROG -t $CONF >/dev/null
		if [ $? -eq 0 ]; then
			if [ -x /usr/sbin/invoke-rc.d ]; then
				invoke-rc.d $NAME start || /bin/true
			else
				/etc/init.d/$NAME start || /bin/true
			fi
		else
			echo "You must review your configuration file"
			echo "$NAME daemon NOT started"
		fi
		;;

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

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0


