#! /bin/bash
# Copyright (c) 1999-2001 SuSE GmbH Nuernberg, Germany.
# Copyright (c) 2002-2004 SuSE Linux AG
#
# Author: Carsten Hoeger <feedback@suse.de>

LC_ALL=POSIX

cpifnewer(){
    # remove files, that do no longer exist
    if [ -d $2 -a "$(echo $2/*)" != "$2/*" ]; then
	for i in $2/*; do
	    if [ ! -e "/$i" ]; then
		echo "removing old or no longer used $i"
		rm -f $i
	    fi
	done
    fi
    test -d $2 || mkdir -p $2
    for i in $1; do
	dst=$2/$(basename $i)
	
	if [ ! -f $dst -a ! -d $dst -a -e $i ]; then
	    echo "copying missing $dst from $i"
	    cp -af $i $dst
	elif [ ! -d $dst -a $i -nt $dst -o $i -ot $dst ]; then
	    echo "updating $dst from $i"
	    cp -af $i $dst
	fi
    done
}

update_db() {
    while test "x$1" != "x" ; do
	pfmap=/etc/postfix/${1%:*}
	mode=${1#*:}
        if [ "$mode" == "$1" ]; then
	    mode=644
        fi
	chmod $mode ${pfmap}
	test -e $pfmap && \
	    if test $pfmap -nt ${pfmap}.db -o ! -e ${pfmap}.db ; then
	       echo "rebuilding ${pfmap}.db"
	       postmap ${pfmap}
	    fi
	chmod $mode ${pfmap}.db
	shift
    done
}

get_alias_maps(){
    test -d /etc/aliases.d && test "$(echo /etc/aliases.d/*)" != "/etc/aliases.d/*" && \
	for i in $(find /etc/aliases.d -maxdepth 1 -type f \
		'!' -regex ".*\.\(db\|rpmsave\|rpmorig\)" \
		'!' -regex ".*/\(\.\|#\).*" \
		'!' -regex ".*~$") ; do
	    echo -n "$i ";
    done
}

warn_user(){
    tput bold
    echo -e "\t*** WARNING ***"
    echo -e $1
    echo -e "\t*** WARNING ***"
    tput sgr0
}

mkchroot(){

    if [ ! -d /var/spool/postfix ]; then
	warn_user "\t/var/spool/postfix does not exist!!!\n\
\tThis should not happen!\n\
\tPlease reinstall package postfix or create this directory!"
	exit 1
    fi
    cd /var/spool/postfix

    if [ "$(echo "$POSTFIX_CHROOT" | tr 'A-Z' 'a-z' )" != "yes" -a \
	"$(echo "$POSTFIX_UPDATE_CHROOT_JAIL" | tr 'A-Z' 'a-z' )" != "no" ]; then
	if [ -d etc ]; then
	    echo "removing postfix chroot environment..."
	fi

	if grep /var/spool/postfix/proc /proc/mounts &> /dev/null; then
	   umount /var/spool/postfix/proc
	fi

	rm -rvf etc lib64 usr var proc
    elif [ "$(echo "$POSTFIX_UPDATE_CHROOT_JAIL" | tr 'A-Z' 'a-z' )" != "no" ]; then
	echo "checking postfix chroot environment..."
	
	if [ -e /lib/security/pam_ldap.so ]; then
	    cpifnewer /etc/openldap/ldap.conf etc/openldap
	fi

	mkdir -p /var/spool/postfix/proc
	if ! grep /var/spool/postfix/proc /proc/mounts &> /dev/null; then
	    mount -o ro -t proc proc /var/spool/postfix/proc
	fi
	
	# PAM
	cpifnewer "/etc/pam.d/*" etc/pam.d
	cpifnewer "/lib64/security/*" lib64/security
	cpifnewer "/lib64/libpam*" lib64
	cpifnewer "/usr/lib64/libcrack.so*" usr/lib64

	# SASL
	cpifnewer /etc/sasldb2 etc
	cpifnewer "/usr/lib64/sasl2/*" usr/lib64/sasl2
	cpifnewer "/usr/lib64/libsasl2*" usr/lib64
	mkdir -p var/run/sasl2
	test -S /var/run/sasl2/mux && ln -f /var/run/sasl2/mux var/run/sasl2/mux

	cpifnewer "/lib64/libnss*" lib64
	cpifnewer "/lib64/libresolv*" lib64
	cpifnewer "/lib64/libdb*" lib64
	cpifnewer "/lib64/libxcrypt*" lib64

	cpifnewer /etc/host.conf etc
	cpifnewer /etc/nsswitch.conf etc
	cpifnewer /etc/resolv.conf etc
	cpifnewer /etc/services etc
	cpifnewer /etc/hosts etc
	cpifnewer /etc/passwd etc

	if [ -L /etc/localtime ]; then
	    if [ -z "$TIMEZONE" -o "$TIMEZONE" == "YAST_ASK" ]; then
		warn_user "\tUnable to setup your timezone!\n\
\tThe logging of the current time in /var/log/mail may be wrong!\n\
\tPlease set the variable TIMEZONE in /etc/sysconfig/clock!"
	    else
		mkdir -p usr/share/zoneinfo/$(dirname $TIMEZONE)
		if [ ! -e /usr/share/zoneinfo/$TIMEZONE ]; then
		    warn_user "\t$TIMEZONE is not a regular timezone or the corresponding\n\
\tfile at /usr/share/zoneinfo does not exist"
		else
		    cp -af /usr/share/zoneinfo/$TIMEZONE usr/share/zoneinfo/$TIMEZONE
		    ln -sf ../usr/share/zoneinfo/$TIMEZONE etc/localtime
		fi
	    fi
	else
	    cpifnewer /etc/localtime etc
	fi
	
	chown -R root /var/spool/postfix/{etc,lib64,usr,var}
    fi
}

gen_main_cf(){
    TMPDIR=$(mktemp -d /tmp/SuSEconfig.postfix.XXXXXX) || exit 1
    PCONF="/usr/sbin/postconf -c $TMPDIR"

    if [ $? -ne 0 ]; then
       warn_user "Can't create temp directory, exiting..."
       exit 1
    fi
    cp -f /etc/postfix/main.cf $TMPDIR/main.cf

    # Some default settings, that seem to be useable, at least to me
    $PCONF -e "mail_spool_directory = /var/mail"
    $PCONF -e "canonical_maps = hash:/etc/postfix/canonical"
    $PCONF -e "virtual_maps = hash:/etc/postfix/virtual"
    $PCONF -e "relocated_maps = hash:/etc/postfix/relocated"
    $PCONF -e "transport_maps = hash:/etc/postfix/transport"
    $PCONF -e "sender_canonical_maps = hash:/etc/postfix/sender_canonical"
    $PCONF -e "masquerade_exceptions = root"
    $PCONF -e "masquerade_classes = envelope_sender, header_sender, header_recipient"
    $PCONF -e "myhostname = $FQHOSTNAME"


    # to be on the save side
    $PCONF -e "daemon_directory = /usr/lib/postfix"
    $PCONF -e "program_directory = /usr/lib/postfix"
    $PCONF -e "readme_directory = /usr/share/doc/packages/postfix/README_FILES"
    $PCONF -e "html_directory = /usr/share/doc/packages/postfix/html"
    $PCONF -e "sample_directory = /usr/share/doc/packages/postfix/samples"
    $PCONF -e "sendmail_path = /usr/sbin/sendmail"
    $PCONF -e "setgid_group = maildrop"
    $PCONF -e "manpage_directory = /usr/share/man"
    $PCONF -e "newaliases_path = /usr/bin/newaliases"
    $PCONF -e "mailq_path = /usr/bin/mailq"

    # activate IPv6
    $PCONF -e "inet_protocols = all"

    if test "$SMTPD_LISTEN_REMOTE" != "yes" ; then
	IFACES="127.0.0.1"
	if [ -n "$(ip addr show lo|grep inet6)" ]; then
		IFACES="$IFACES ::1"
	fi
	$PCONF -e "inet_interfaces = $IFACES"
    else
        $PCONF -e "inet_interfaces = all"
    fi

    test -n "$POSTFIX_MASQUERADE_DOMAIN" && \
        MASQ_DOMS=$POSTFIX_MASQUERADE_DOMAIN
    if [ -n "$FROM_HEADER" -a "$FROM_HEADER" != "YAST_ASK" ]; then
        if [ -n "$MASQ_DOMS" ]; then
            MASQ_DOMS="$MASQ_DOMS, $FROM_HEADER"
        else 
            MASQ_DOMS="$FROM_HEADER"
        fi
    fi
    $PCONF -e "masquerade_domains = $MASQ_DOMS"
    
    if test -z "$POSTFIX_LOCALDOMAINS"; then
	$PCONF -e 'mydestination = $myhostname, localhost.$mydomain'
    else
	$PCONF -e "mydestination = $POSTFIX_LOCALDOMAINS"
    fi

    # this overrides the previous
    if test "$POSTFIX_NULLCLIENT" == "yes"; then
	$PCONF -e "mydestination = "
    fi

    if test "$POSTFIX_DIALUP" == "yes"; then
	$PCONF -e "defer_transports = smtp"
    else
	$PCONF -e "defer_transports = "
    fi

    if test  "$POSTFIX_NODNS" == "yes"; then
	$PCONF -e "disable_dns_lookups = yes"
    else
	$PCONF -e "disable_dns_lookups = no"
    fi
    if test -n "$POSTFIX_RELAYHOST"; then
	$PCONF -e "relayhost = $POSTFIX_RELAYHOST"
    else
	$PCONF -e "relayhost = "
    fi

    case "$POSTFIX_MDA" in
	procmail)
	    echo 1>&2 "Setting up procmail as MDA..."
	    if [ ! -x /usr/bin/procmail ]; then
		warn_user 1>&2 "procmail is not installed, using local as MDA!"
		$PCONF -e "mailbox_command = "
		$PCONF -e "mailbox_transport = "
	    else
		$PCONF -e "mailbox_command = /usr/bin/procmail"
		$PCONF -e "mailbox_transport = "
	    fi
	    ;;
	cyrus)
	    echo 1>&2 "Setting up cyrus-imapd via lmtp as MDA..."
	    if [ ! -x /usr/lib/cyrus/bin/lmtpd ]; then
		warn_user 1>&2 "cyrus-imapd is not installed, using local as MDA!"
		$PCONF -e "mailbox_command = "
		$PCONF -e "mailbox_transport = "
	    else
		LMTPUNIX=$(grep -E "^[[:space:]]*lmtpunix.*" /etc/cyrus.conf)
		if [ -z "$LMTPUNIX" ]; then
		    warn_user 1>&2 "you have to add\n\
lmtpunix      cmd=\"lmtpd\" listen=\"/var/lib/imap/socket/lmtp\" prefork=1\n\
to /etc/cyrus.conf"
		else
		    if [ -z "$(echo $LMTPUNIX | grep -E '/var/lib/imap/socket/lmtp')" ]; then
			warn_user 1>&2 "the socket to listen on is wrong in /etc/cyrus.conf\n\
use listen=\"/var/lib/imap/socket/lmtp\" instead!"
		    fi
		fi
		$PCONF -e "mailbox_command = "
		$PCONF -e "mailbox_transport = lmtp:unix:/var/lib/imap/socket/lmtp"
		if [ -z "$(id postfix | grep -E 'groups=.*mail')" ]; then
			warn_user 1>&2 "adding postfix user to group mail"
			usermod -G mail postfix
		fi
	    fi
	    ;;
	local|*)
	    echo 1>&2 "Setting up postfix local as MDA..."
	    $PCONF -e "mailbox_command = "
	    $PCONF -e "mailbox_transport = "
	    ;;
    esac

    case "$POSTFIX_BASIC_SPAM_PREVENTION" in
	medium)
	    echo 1>&2 "Setting up medium SPAM protection..."
	    $PCONF -e "smtpd_sender_restrictions = hash:/etc/postfix/access, reject_unknown_sender_domain"
	    if test -n "$POSTFIX_RBL_HOSTS"; then
		rblhosts=$(echo ${POSTFIX_RBL_HOSTS//,/ })
		clnt_restrictions=""
		for i in $rblhosts; do
		    if [ -z "$clnt_restrictions" ]; then
			clnt_restrictions="reject_rbl_client $i"
		    else
			clnt_restrictions="$clnt_restrictions, reject_rbl_client $i"
		    fi
		done
		$PCONF -e "smtpd_client_restrictions = $clnt_restrictions"
	    else
		$PCONF -e "smtpd_client_restrictions ="
	    fi
	    $PCONF -e "smtpd_helo_required = yes"
	    $PCONF -e "smtpd_helo_restrictions = "
	    $PCONF -e "strict_rfc821_envelopes = no"
	    $PCONF -e "smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination "
	    ;;
	hard)
	    echo 1>&2 "Setting up hard SPAM protection..."
	    $PCONF -e "smtpd_sender_restrictions = hash:/etc/postfix/access, reject_unknown_sender_domain"
	    if test -n "$POSTFIX_RBL_HOSTS"; then
		rblhosts=$(echo ${POSTFIX_RBL_HOSTS//,/ })
		clnt_restrictions=""
		for i in $rblhosts; do
		    if [ -z "$clnt_restrictions" ]; then
			clnt_restrictions="reject_rbl_client $i"
		    else
			clnt_restrictions="$clnt_restrictions, reject_rbl_client $i"
		    fi
		done
		$PCONF -e "smtpd_client_restrictions = permit_mynetworks, $clnt_restrictions, reject_unknown_client"

	    else
		$PCONF -e \
		    "smtpd_client_restrictions = permit_mynetworks, reject_unknown_client"
	    fi
	    $PCONF -e "smtpd_helo_required = yes"
	    $PCONF -e "smtpd_helo_restrictions = permit_mynetworks, reject_invalid_hostname"
	    $PCONF -e "strict_rfc821_envelopes = yes"
	    $PCONF -e "smtpd_recipient_restrictions = permit_mynetworks, reject_unauth_destination"
	    ;;
	*)
	    if test "$POSTFIX_BASIC_SPAM_PREVENTION" != "off"; then
		warn_user 1>&2 "$POSTFIX_BASIC_SPAM_PREVENTION is an invalid value for POSTFIX_BASIC_SPAM_PREVENTION\n\
using \"off\" instead!"
	    fi
	    echo 1>&2 "Setting SPAM protection to \"off\"..."
	    $PCONF -e "smtpd_sender_restrictions = hash:/etc/postfix/access"
	    $PCONF -e "smtpd_client_restrictions ="
	    $PCONF -e "smtpd_helo_required = no"
	    $PCONF -e "smtpd_helo_restrictions ="
	    $PCONF -e "strict_rfc821_envelopes = no"
	    $PCONF -e "smtpd_recipient_restrictions = permit_mynetworks,reject_unauth_destination"
	    ;;
    esac

    if test "$POSTFIX_SMTP_AUTH" == "yes"; then
	$PCONF -e "smtp_sasl_auth_enable = yes"
	$PCONF -e "smtp_sasl_security_options = $POSTFIX_SMTP_AUTH_OPTIONS"
	$PCONF -e "smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd"
    else
	$PCONF -e "smtp_sasl_auth_enable = no"
    fi

    if test "$POSTFIX_SMTP_AUTH_SERVER" == "yes"; then
	if [ -f /usr/lib64/sasl2/smtpd.conf ]; then
	    grep saslauthd /usr/lib64/sasl2/smtpd.conf >/dev/null && {
		checkproc -p /var/run/sasl2/mux.pid /usr/sbin/saslauthd || {
		    warn_user 1>&2 "You are using saslauthd as pwcheck_method in /usr/lib64/sasl2/smtpd.conf,\n\
but saslauthd is not running."
		}
	    }
	else
	    warn_user 1>&2 "You have activated POSTFIX_SMTP_AUTH_SERVER, but you don't have /usr/lib64/sasl2/smtpd.conf"
	fi
	$PCONF -e "smtpd_sasl_auth_enable= yes"
        touch -m -d "1 minute ago" $TMPDIR/main.cf
	CURRENT=$($PCONF -h smtpd_client_restrictions)
	$PCONF -e "smtpd_client_restrictions= permit_sasl_authenticated, $CURRENT"
        touch -m -d "1 minute ago" $TMPDIR/main.cf
	CURRENT=$($PCONF -h smtpd_recipient_restrictions)
	$PCONF -e "smtpd_recipient_restrictions= permit_sasl_authenticated, $CURRENT"
    else
	$PCONF -e "smtpd_sasl_auth_enable= no"
    fi


    if test "$POSTFIX_SMTP_TLS_SERVER" == "yes"; then
	grep -E '^smtps' /etc/services >/dev/null || {
	    warn_user 1>&2 "adding service \"smtps\" to /etc/services"
	    echo "smtps           465/tcp         # smtp over SSL" >> /etc/services
	}
	$PCONF -e "smtpd_use_tls = yes"
	$PCONF -e "smtpd_tls_CAfile = $POSTFIX_SSL_PATH/$POSTFIX_TLS_CAFILE"
	$PCONF -e "smtpd_tls_cert_file = $POSTFIX_SSL_PATH/$POSTFIX_TLS_CERTFILE"
	$PCONF -e "smtpd_tls_key_file = $POSTFIX_SSL_PATH/$POSTFIX_TLS_KEYFILE"
	$PCONF -e "smtpd_tls_received_header = yes"
	$PCONF -e "tls_daemon_random_source = dev:/dev/urandom"
	$PCONF -e "tls_random_source = dev:/dev/urandom"
	$PCONF -e "relay_clientcerts = hash:/etc/postfix/relay_ccerts"
	$PCONF -e "smtpd_tls_ask_ccert = yes"
        touch -m -d "1 minute ago" $TMPDIR/main.cf
	CURRENT=$($PCONF -h smtpd_recipient_restrictions)
	$PCONF -e "smtpd_recipient_restrictions = permit_tls_clientcerts, $CURRENT"
    else
	$PCONF -e "smtpd_use_tls = no"
    fi

    if test "$POSTFIX_SMTP_TLS_CLIENT" == "yes"; then
	$PCONF -e "smtp_use_tls = yes"
	test -s "$POSTFIX_SSL_PATH/$POSTFIX_TLS_CAFILE" && \
	    $PCONF -e "smtp_tls_CAfile = $POSTFIX_SSL_PATH/$POSTFIX_TLS_CAFILE"
	test -s "$POSTFIX_SSL_PATH/$POSTFIX_TLS_CERTFILE" && \
	    $PCONF -e "smtp_tls_cert_file = $POSTFIX_SSL_PATH/$POSTFIX_TLS_CERTFILE"
	test -s "$POSTFIX_SSL_PATH/$POSTFIX_TLS_KEYFILE" && \
	    $PCONF -e "smtp_tls_key_file = $POSTFIX_SSL_PATH/$POSTFIX_TLS_KEYFILE"
    else
	$PCONF -e "smtp_use_tls = no"
    fi

    ALLMAPS="hash:/etc/aliases"
    for i in $(get_alias_maps); do
	ALLMAPS="${ALLMAPS}, hash:$i"
    done
    $PCONF -e "alias_maps = $ALLMAPS"

    for i in $(echo ${!POSTFIX_ADD_*}); do
        touch -m -d "1 minute ago" $TMPDIR/main.cf
	pfkey=$(echo ${i#POSTFIX_ADD_} | tr '[:upper:]' '[:lower:]')
	pfval=$(eval "echo \$$i")
	if [ -z "$($PCONF $pfkey 2>/dev/null)" ]; then
	    warn_user 1>&2 "unknown parameter $i ignored"
	else
	    $PCONF -e "$pfkey = $pfval"
	fi
    done

    cat $TMPDIR/main.cf
    rm -rf $TMPDIR
}

gen_master_cf(){
    export POSTFIX_LAPTOP
    export POSTFIX_CHROOT
    export POSTFIX_NULLCLIENT
    export USE_AMAVIS
    export POSTFIX_SMTP_TLS_SERVER
    export POSTFIX_SMTP_TLS_CLIENT

    perl -e 'use strict;

my $mcf = "/etc/postfix/master.cf";
my $line;

my $laptop = 
    defined $ENV{POSTFIX_LAPTOP} ? $ENV{POSTFIX_LAPTOP} : "no";
my $nullclient = 
    defined $ENV{POSTFIX_NULLCLIENT} ? $ENV{POSTFIX_NULLCLIENT} : "no";
my $chroot = 
    defined $ENV{POSTFIX_CHROOT} ? $ENV{POSTFIX_CHROOT} : "yes";
my $use_amavis =
    defined $ENV{USE_AMAVIS} ? $ENV{USE_AMAVIS} : "no";
my $tlsserver = 
    defined $ENV{POSTFIX_SMTP_TLS_SERVER} ? $ENV{POSTFIX_SMTP_TLS_SERVER} : "no";
my $tlsclient = 
    defined $ENV{POSTFIX_SMTP_TLS_CLIENT} ? $ENV{POSTFIX_SMTP_TLS_CLIENT} : "no";


$laptop = lc($laptop);
$chroot = lc($chroot);
$nullclient = lc($nullclient);
$use_amavis = lc($use_amavis);
$tlsserver = lc($tlsserver);
$tlsclient = lc($tlsclient);

open(MCF,"<$mcf") || die "unable to open $mcf: $!";

while( <MCF> ) {
    chomp;

    if( /\#?\s*(smtp\s+inet.*?smtpd)/ ) {
	if ($nullclient eq "yes") {
	    $line = "#".$1;
	} else {
	    $line = $1;
	}
        if ( $use_amavis eq "yes" ) {
	    $line =~ /(\#?\s*smtp\s+inet\s+[yn-]?\s+[yn-]?\s+[yn-]?\s+[0-9?yn-]?\s+)[0-9-]?(.*)/;
            $line = $1."2".$2." -o content_filter=smtp:[127.0.0.1]:10024";
        } else {
	    $line =~ /(\#?\s*smtp\s+inet\s+[yn-]?\s+[yn-]?\s+[yn-]?\s+[0-9?yn-]?\s+)[0-9-]?(.*)/;
            $line = $1."-".$2;
        }
    } elsif( /\#?\s*(local\s+unix.*)/ ) {
	if ($nullclient eq "yes") {
	    $line = "#".$1;
	} else {
	    $line = $1;
	}
    } elsif( /\#?\s*(localhost:10025\s+inet.*)/ ) {
       if ( $use_amavis ne "yes" ) {
            $line = "#".$1;
       } else {
            $line = $1;
       }
    } elsif( /\#?\s*(tlsmgr.*)/ ) {
       if ( $tlsclient ne "yes" && $tlsserver ne "yes" ) {
            $line = "#".$1;
       } else {
            $line = $1;
       }
    } elsif( /\#?\s*(smtps\s+inet.*?smtpd)/ ) {
       if ( $tlsserver ne "yes" ) {
            $line = "#".$1." -o smtpd_tls_wrappermode=yes";
       } else {
            $line = $1." -o smtpd_tls_wrappermode=yes";
       }
       if ( $use_amavis eq "yes" ) {
	    $line =~ /(\#?\s*smtps\s+inet\s+[yn-]?\s+[yn-]?\s+[yn-]?\s+[0-9?yn-]?\s+)[0-9-]?(.*)/;
            $line = $1."2".$2." -o content_filter=smtp:[127.0.0.1]:10024";
       } else {
	    $line =~ /(\#?\s*smtps\s+inet\s+[yn-]?\s+[yn-]?\s+[yn-]?\s+[0-9?yn-]?\s+)[0-9-]?(.*)/;
            $line = $1."-".$2;
       }
    } elsif( /^(\#?\s*(?:pickup|qmgr)\s+)(?:fifo|unix)(\s+.*)/ ) {
       if ( $laptop eq "yes" ) {
            $line = $1."unix".$2;
       } else {
            $line = $1."fifo".$2;
       }
    } else {
	$line = $_;
    }

    if( $line =~ /^\#/ ) {
	print $line."\n";
	next;
    }

    my $match = 0;
    foreach my $serv ( ( "smtp", "pickup", "cleanup", "qmgr", "rewrite",
			 "bounce", "defer", "showq", "error", "virtual",
			 "lmtp", "smtps", "tlsmgr", "localhost:10025" ) ) {
	if( $line =~ /^$serv\s+/ ) {
	    $line =~ /(^$serv\s+\w+\s+[yn-]?\s+[yn-]?\s+)[yn-]?(.*)/;
	    print $1.( $chroot eq "yes" ? "y" : "n" ).$2."\n";
	    $match = 1;
	} else {
	    next;
	}
    }
    print $line."\n" if ! $match;
}'

}

update_cf() {
    while test "x$1" != "x" ; do
	if [ ! -f $r/etc/postfix/${1}.SuSEconfig ]; then
	   eval gen_${1/\./_} > $r/etc/postfix/${1}.SuSEconfig
	  	test -s $r/etc/postfix/${1}.SuSEconfig || {
	  	    warn_user "Writing $r/etc/postfix/${1}.SuSEconfig failed, exiting..."
	  	    exit 1
	  	}
	  	check_md5_and_move $r/etc/postfix/$1
	else
	   warn_user "Found /etc/postfix/${1}.SuSEconfig, exiting..."
	   exit 1
	fi
	shift
    done
}

restore_cf() {
    while test "x$1" != "x" ; do
	warn_user "/etc/postfix/${1}: zero file size or missing, restoring
from /var/adm/backup/postfix/${1}"
	if [ ! -s /var/adm/backup/postfix/$1 ]; then
	    warn_user "/var/adm/backup/postfix/${1}: zero file size or missing, exiting..."
	    exit 1
	fi
	rm -f /var/adm/SuSEconfig/md5/etc/postfix/$1
	cp --remove-destination /var/adm/backup/postfix/$1 /etc/postfix/$1
	
	update_cf $1
	shift
    done
}

gen_CA() {
    openssl=/usr/bin/openssl
    sslpath=$POSTFIX_SSL_PATH
    sslconfig=$sslpath/openssl_postfix.conf
    date="$(date)"

    oldmask=$(umask)
    umask 077
    mkdir -p $sslpath/private
    mkdir -p $sslpath/certs
    mkdir -p $sslpath/newcerts

    test -f $sslpath/serial || \
	echo 01 > $sslpath/serial
    touch $sslpath/index.txt
    sed -e "s/@POSTFIX_SSL_COUNTRY@/$POSTFIX_SSL_COUNTRY/" \
	-e "s/@POSTFIX_SSL_STATE@/$POSTFIX_SSL_STATE/" \
	-e "s/@POSTFIX_SSL_LOCALITY@/$POSTFIX_SSL_LOCALITY/" \
	-e "s/@POSTFIX_SSL_ORGANIZATION@/$POSTFIX_SSL_ORGANIZATION/" \
	-e "s/@POSTFIX_SSL_ORGANIZATIONAL_UNIT@/$POSTFIX_SSL_ORGANIZATIONAL_UNIT/" \
	-e "s/@POSTFIX_SSL_COMMON_NAME@/$POSTFIX_SSL_COMMON_NAME/" \
	-e "s/@POSTFIX_SSL_EMAIL_ADDRESS@/$POSTFIX_SSL_EMAIL_ADDRESS/" \
	-e "s/@RANDOM@/${RANDOM}${RANDOM}/" \
	-e "s/@COMMENT@/generated by SuSEconfig.postfix at $date/" \
	/etc/postfix/openssl_postfix.conf.in > $sslconfig

    echo "creating CA request/certificate..."
    $openssl req -days 2000 -config $sslconfig -new -x509 -nodes \
	-keyout $sslpath/private/cakey.pem -out $sslpath/$POSTFIX_TLS_CAFILE 2>/dev/null || {
	echo "error creating CA request/certificate"
	rm -rf $sslpath
	umask $oldmask
	return
    }
	    
    echo "creating certificate request..."
    $openssl req -config $sslconfig -new -nodes -keyout \
	$sslpath/$POSTFIX_TLS_KEYFILE -out $sslpath/certs/postfixreq.pem 2>/dev/null || {
	echo "error creating certificate request"
	rm -rf $sslpath
	umask $oldmask
	return
    }
    
    echo "signing server certificate..."
    $openssl ca -config $sslconfig -notext -batch \
	-out $sslpath/$POSTFIX_TLS_CERTFILE \
	-infiles $sslpath/certs/postfixreq.pem 2>/dev/null || {
	echo "error signing server certificate"
	rm -rf $sslpath
	umask $oldmask
	return
    }
    
    chmod 755 $sslpath
    chmod 755 $sslpath/certs
    chmod 644 $sslpath/cacert.pem
    umask $oldmask
}

###############################################################################
#################################### MAIN #####################################
###############################################################################

r=$ROOT

test -s $r/etc/sysconfig/postfix || {
    echo "No $r/etc/sysconfig/postfix found."
    exit 1
}
. $r/etc/sysconfig/postfix

# this file contains generic mail setup information
test -s $r/etc/sysconfig/mail || {
    echo "No $r/etc/sysconfig/mail found."
    exit 1
}
. $r/etc/sysconfig/mail

# We may need TIMEZONE for chroot setup
test -s $r/etc/sysconfig/clock && . $r/etc/sysconfig/clock

# Try to get a valid hostname...
FQHOSTNAME=$(hostname -f)
# check whether hostname contains at least one dot...
echo $FQHOSTNAME | grep "\." >/dev/null || FQHOSTNAME=""

test -z "$FQHOSTNAME" && {
    # still no valid hostname? Then read /etc/HOSTNAME
    test -s $r/etc/HOSTNAME && read -t 1 FQHOSTNAME < $r/etc/HOSTNAME
    # check whether hostname contains at least one dot...
    echo $FQHOSTNAME | grep "\." >/dev/null || FQHOSTNAME=""
    # still no valid hostname? :-( set hostname to linux.local
    test -z "$FQHOSTNAME" && FQHOSTNAME=linux.local 
}

# check whether we want to use amavis
if [ -x /usr/sbin/amavisd ]; then
    test -s $r/etc/sysconfig/amavis && . $r/etc/sysconfig/amavis
fi

test -f $r/lib/YaST/SuSEconfig.functions || {
    echo "ERROR - can not find $r/lib/YaST/SuSEconfig.functions!!"
    echo "This should not happen.  Exit..."
    exit 1
}
. $r/lib/YaST/SuSEconfig.functions


# call mkchroot. The conditions what to do take place in this function.
mkchroot

# restore main.cf and master.cf, if they had been removed by accident
test -z "$r" && {
    if [ ! -s /etc/postfix/main.cf ]; then
	restore_cf main.cf
    fi
    
    if [ ! -s /etc/postfix/master.cf ]; then
	restore_cf master.cf
    fi
}

if test -z "$r" && test "$POSTFIX_SMTP_TLS_SERVER" == yes ; then
    test -d $POSTFIX_SSL_PATH || gen_CA
fi

if test -z "$r" && test "$POSTFIX_UPDATE_MAPS" == yes ; then
    test -e /etc/aliases && \
        if test /etc/aliases -nt /etc/aliases.db \
                -o ! -e /etc/aliases.db ; then
                echo "Rebuilding /etc/aliases.db."
                /usr/bin/newaliases
        fi
    update_db $POSTFIX_MAP_LIST

    for i in $(get_alias_maps); do
	if test $i -nt $i.db -o ! -e $i.db; then
	    echo "Rebuilding $i.db"
	    /usr/sbin/postalias $i
	fi
    done
	
    /usr/sbin/postfix reload > /dev/null 2>&1
fi


if test "$MAIL_CREATE_CONFIG" != "yes"; then
    exit;
fi


# Note: Because gen_main_cf and gen_master_cf always use original main.cf
# and master.cf as input base, we won't get a .SuSEconfig file, normally

test -z "$r" && update_cf master.cf main.cf

