#!/bin/sh -e

#export DEBCONF_DEBUG=developer
CONFIGFILE=/etc/dbmail/dbmail.conf
DEBIANCONF=/etc/default/dbmail
MAILNAMEFILE=/etc/mailname

. /usr/share/debconf/confmodule

read_config() {
	for line in `grep -E '^[^# $]' $CONFIGFILE|sed 's/[\t ]//g'|awk -F'#' '{print $1}'`; do
		NEWSECTION=`echo $line|grep '^\['|sed 's/\(\[\)\(.*\)\(\]\)/\2/'`
		if [ -n "$NEWSECTION" ]; then
			SECTION=`echo $NEWSECTION|tr '[A-Z]' '[a-z]'`
		else
			key=`echo $line|cut -f1 -d'='|tr '[A-Z]' '[a-z]'`
			val=`echo $line|cut -f2- -d'='`
			if [ -n "$val" ]; then
				eval "db_set dbmail/$SECTION/$key \"$val\"" || true
			fi
		fi	
	done
}

get_hostname() {
	HOSTNAME=localdomain
	if [ -e $MAILNAMEFILE ]; then
		HOSTNAME=`cat $MAILNAMEFILE`
	else
		HOSTNAME=`hostname --fqdn 2>/dev/null`
	fi
}

init_config() {
	if [ -e $CONFIGFILE ]; then
		read_config
	fi	
	db_get dbmail/dbmail/postmaster
	if [ -z $RET ]; then
		get_hostname
		db_set dbmail/dbmail/postmaster "postmaster@$HOSTNAME"
	fi

	if [ -e $DEBIANCONF ]; then
		. $DEBIANCONF
		# setup some defaults
		db_set dbmail/start_imapd "false"
		db_set dbmail/start_lmtpd "false"
		db_set dbmail/start_pop3d "false"
		db_set dbmail/start_sieve "false"
		# overwrite them with the values in the config file
		[ "$START_IMAPD" ] && db_set dbmail/start_imapd "$START_IMAPD" || true
		[ "$START_LMTPD" ] && db_set dbmail/start_lmtpd "$START_LMTPD" || true
		[ "$START_POP3D" ] && db_set dbmail/start_pop3d "$START_POP3D" || true
		[ "$START_SIEVE" ] && db_set dbmail/start_sieve "$START_SIEVE" || true
	fi
}

db_capb backup

STATE=1
LASTSTATE=5
while [ 1 ]; do

	[ "$STATE" = "0" ] && break
	[ "$STATE" = "$LASTSTATE" ] && break

	case "$STATE" in
	1)
		db_input medium dbmail/do_debconf || true
	;;	
	2)
		db_get dbmail/do_debconf
		if [ "$RET" = "false" ]; then
			break
		fi
		init_config
		db_input medium dbmail/dbmail/host || true
		db_input medium dbmail/dbmail/db || true
		db_input medium dbmail/dbmail/user || true
		db_input medium dbmail/dbmail/pass || true
		db_input medium dbmail/dbmail/postmaster || true
		db_input medium dbmail/start_lmtpd || true
		db_input medium dbmail/start_imapd || true
		db_input medium dbmail/start_pop3d || true
		db_input medium dbmail/start_sieve || true
		db_input medium dbmail/dbmail/authdriver || true
	;;
	3)
		db_get dbmail/dbmail/authdriver
		if [ "$RET" = "sql" ]; then
			break
		fi
		db_input medium dbmail/ldap/hostname || true
		db_input medium dbmail/ldap/port || true
		db_input medium dbmail/ldap/base_dn || true
		db_input low dbmail/ldap/field_uid|| true
		db_input low dbmail/ldap/field_cid || true
		db_input medium dbmail/ldap/bind_anonymous || true
	;;
	4)
		db_get dbmail/ldap/bind_anonymous
		if [ "$RET" = "true" ]; then
			break
		fi
		db_input medium dbmail/ldap/bind_dn || true
		db_input medium dbmail/ldap/bind_pw || true
	;;

	esac

	if db_go; then
		STATE=$(($STATE+1))
	else
		STATE=$(($STATE-1))
	fi
done	
	
exit 0	



syntax highlighted by Code2HTML, v. 0.9.1