#!/bin/sh

set -e

ucf_register_templates() {
    for template in /etc/pmg/templates/*; do
        [ -e "$template" ] || continue;
        template_base=$(basename "${template}")
        if echo "${template_base}" | grep -q '\.ucf-'; then
            continue
        fi
        if [ -e "/var/lib/pmg/templates/${template_base}" ]; then
            ucf "/var/lib/pmg/templates/${template_base}" "${template}"
            ucfr pmg-api "${template}"
        else
            echo "template '${template}' not shipped by pmg-api."
        fi
    done
}

# TODO: remove with 10.0
migrate_pmg_smtp_filter() {
    systemd-sysusers

    install -d --owner pmg-smtp-filter --group pmg /var/lib/pmg/spamassassin
    if [ -e /root/.spamassassin ]; then
        printf "\nMigrating spamassassin user state directory\n"
        cp -a /root/.spamassassin/. /var/lib/pmg/spamassassin/
    fi
    if [ -e /var/lib/pmg/decode_short_urls.db ]; then
        printf "Migrating spamassassin decode_short_url cache\n"
        mv /var/lib/pmg/decode_short_urls.db /var/lib/pmg/spamassassin/
    fi
    if [ -e /root/.razor ]; then
        printf "Migrating razor home directory\n"
        install -d /var/lib/pmg/spamassassin/.razor
        cp -a /root/.razor/. /var/lib/pmg/spamassassin/.razor/
    fi
    chown -Rv pmg-smtp-filter:pmg /var/lib/pmg/spamassassin

    printf "Adjusting group ownership of the mail spool, this might take a while\n"
    # no -v: the spool can hold millions of mails
    chgrp -R pmg /var/spool/pmg || true
    chmod -R g+w /var/spool/pmg || true

    chgrp -Rv pmg /etc/pmg/dkim
    chmod -Rv g+rX /etc/pmg/dkim

    if [ -e /etc/pmg/ldap.conf ]; then
        chgrp -v pmg /etc/pmg/ldap.conf
    fi
}

case "$1" in
    triggered)

        test -e /proxmox_install_mode && exit 0;

        # Note: reload-or-try-restart fails if service is not active
        for service in pmgdaemon pmgproxy pmg-smtp-filter pmgpolicy pmgtunnel pmgmirror; do
            if systemctl --quiet is-active $service.service ; then
                deb-systemd-invoke reload-or-try-restart $service.service >/dev/null || true
            fi
        done

        exit 0
    ;;

    configure)

        BETA_SOURCES="/etc/apt/sources.list.d/pmg-test-for-beta.sources"
        if test -f "$BETA_SOURCES" && test -n "$2" && dpkg --compare-versions "$2" 'lt' '9.0.1' && dpkg --compare-versions "$2" 'gt' '9.0~~'; then
            printf "\nNOTE: Removing the pmg-test repository, which was added during the beta phase.\nYou can (re-)add repositories on the web UI (Administration -> Repositories)\n\n"
            rm -v "$BETA_SOURCES" || true
        fi

        if test ! -e /proxmox_install_mode ; then

            # pick up changed unit files (like the new User= on pmg-smtp-filter/pmgpolicy)
            # before any service is (re)started below, so none comes back on the stale unit
            if [ -d /run/systemd/system ]; then
                systemctl --system daemon-reload >/dev/null || true
            fi

            # TODO: remove with 10.0
            if test -n "$2" && dpkg --compare-versions "$2" 'lt' '9.0.11~'; then
                migrate_pmg_smtp_filter
            fi

            pmgconf="/etc/pmg/pmg.conf"
            if test -n "$2" && dpkg --compare-versions "$2" 'lt' '8.0.2'; then
                # on upgrade add pre 8.0 default values for advfilter, use_awl and use_bayes
                # TODO: remove with 10.0
                if test ! -e $pmgconf ; then
                    # if the config does not exist at all, fill with previous default configs
                    printf "section: admin\n\tadvfilter 1\n" > $pmgconf
                    printf "\nsection: spam\n\tuse_bayes 1\n\tuse_awl 1\n" >> $pmgconf
                else
                    if ! grep -qP '\s+advfilter' $pmgconf ; then
                        echo "hard-code old default for 'advfilter'"
                        if ! grep -q '^section: admin$' $pmgconf ; then
                            printf "\nsection: admin" >> $pmgconf
                        fi
                        sed -i '/^section: admin$/a\\tadvfilter 1' $pmgconf
                    fi

                    if ! grep -q '^section: spam$' $pmgconf ; then
                        printf "\nsection: spam" >> $pmgconf
                    fi
                    if ! grep -qP '^\s+use_bayes\s' $pmgconf ; then
                        echo "hard-code old default for 'use_bayes'"
                        sed -i '/^section: spam$/a\\tuse_bayes 1' $pmgconf
                    fi
                    if ! grep -qP '^\s+use_awl\s' $pmgconf ; then
                        echo "hard-code old default for 'use_awl'"
                        sed -i '/^section: spam$/a\\tuse_awl 1' $pmgconf
                    fi
                fi
            fi

            pmgconfig init || true
            pmgdb init || true

            ucf_register_templates
            pmgconfig sync --restart || true

            if [ -z "$2" ]; then
                if systemctl --quiet is-active pmgpolicy.service ; then
                    deb-systemd-invoke reload-or-try-restart postgresql.service >/dev/null || true
                fi
                deb-systemd-invoke restart postfix.service >/dev/null || true
            fi

            pmgdb update  >/dev/null 2>&1 &

            update-mime-database /usr/share/mime

        else
            # rewrite banner
            pmgbanner || true
        fi

        if ! systemctl --quiet is-enabled clamav-freshclam.service ; then
            echo "Enabling clamav-freshclam to keep signatures updated"
            deb-systemd-invoke enable clamav-freshclam.service >/dev/null 2>&1 || true
        fi

        if ! systemctl --quiet is-enabled clamav-daemon.service ; then
            echo "Enabling clamav-daemon as antivirus"
            deb-systemd-invoke enable clamav-daemon.service >/dev/null 2>&1 || true
        fi

        if test -n "$2" && dpkg --compare-versions "$2" 'lt' '8.2.0'; then
            old_score_location=/var/cache/pmg-scores.cf
            new_score_location=/etc/mail/spamassassin/pmg-scores.cf.new
            if test -e "$old_score_location"; then
                if ! test -e "$new_score_location"; then
                    echo "moving $old_score_location to $new_score_location"
                    mv "$old_score_location" "$new_score_location"
                else
                    echo "both $old_score_location and $new_score_location exist - please review manually"
                fi
            fi
        fi
    ;;

    abort-upgrade)
        ucf_register_templates
    ;;

    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#

if test ! -e /proxmox_install_mode ; then
    for service in pmgdaemon pmgproxy; do
        if [ -n "$2" ]; then
            # Note: reload-or-try-restart fails if service is not active
            if systemctl --quiet is-active $service.service ; then
                deb-systemd-invoke reload-or-try-restart $service.service >/dev/null || true
            fi
        else
            deb-systemd-invoke start $service.service > /dev/null || true
        fi
    done
fi

# TODO: remove with 10.0
# re-own SpamAssassin state that the still-root filter wrote after the first migration pass
# walked the tree; the spool is skipped, as only root tools (deliver, purge, sync) handle it
if test ! -e /proxmox_install_mode && test -n "$2" \
    && dpkg --compare-versions "$2" 'lt' '9.0.12~'; then
    if test -d /var/lib/pmg/spamassassin; then
        find /var/lib/pmg/spamassassin -uid 0 -exec chown -v pmg-smtp-filter:pmg {} + || true
    fi
fi

exit 0
