# Common postfix maintscripts functions
#
# note: this file is used by old (3.9.0) postfix prerm scripts!

DYNAMICMAPS=/etc/postfix/dynamicmaps.cf

addmap() { # used by old postinst script
    map=$1 mkmap=$2
    if ! grep -q "^$map[[:space:]]" $DYNAMICMAPS; then
	 echo "Adding $map map entry to $DYNAMICMAPS"
	 echo "$map		postfix-$map.so		dict_${map}_open	$mkmap" >> $DYNAMICMAPS
    fi
}

postinst_addmap() {
    [ configure = "$1" ] || return 0
    map=${DPKG_MAINTSCRIPT_PACKAGE#*-}
    case "$map" in
	(cdb|lmdb) mkmap="mkmap_${map}_open" ;;
	(*) mkmap= ;;
    esac
    addmap $map $mkmap
    if postconf -h alias_database | grep -q "\\b$map:"; then
	runnewaliases
    fi
    touch /var/spool/postfix/restart
}

delmap() { # used by old prerm script
    map=$1
    if grep -q "^$map[[:space:]]" $DYNAMICMAPS; then
	 echo "Removing $map map entry from $DYNAMICMAPS"
	 sed -i "/^$map[[:space:]]/d" $DYNAMICMAPS
    fi
}

prerm_delmap() {
    [ remove = "$1" -o purge = "$1" ] || return 0
    map=${DPKG_MAINTSCRIPT_PACKAGE#*-}
    delmap $map
}

runnewaliases() {
    db_get postfix/main_mailer_type && mailer="$RET"
    if [ "$mailer" != "No configuration" ] || [ -f /etc/postfix/main.cf ]; then
        db_fget postfix/newaliases run || true
        if ( $RET ); then
            echo "Running newaliases"
            rm -f /etc/aliases.db   # handle the roll to db2.0
            # newaliases chokes if hostname not set
            # newaliases is equivalent to postalias $(postconf -hx alias_database)
            # and in debootstrap, newaliases == /bin/true...
            if [ -z "$(postconf -hx myhostname||true)" ]; then
                cp -a main.cf main.cf.dpkg.$$
                postconf -e 'myhostname=debian'
                newaliases
                db_fset postfix/newaliases run false
                mv main.cf.dpkg.$$ main.cf
            else
                newaliases
                db_fset postfix/newaliases run false
            fi
        fi
    fi
}
