#!/bin/sh
# postinst script for trutz-py3-lib.
#
# 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>
#        * <postinst> 'abort-remove'
#        * <deconfigured's-postinst> 'abort-deconfigure' 'in-favour'
#          <failed-install-package> <version> 'removing'
#          <conflicting-package> <version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package.


case "$1" in
    configure)
        # Repair existing OpenPGP keyrings: keys generated by the root-run
        # backend before trutz-py3-lib 2.0.6 are root-owned, but the mail
        # milters run as User=postfix and then fail with "No secret key"
        # (mails go out unsigned, incoming mail cannot be decrypted).
        # Idempotent; only the keyring is touched, NOT all of
        # /var/lib/trutz-mail (the Roundcube DB there belongs to www-data).
        PGP_DIR=/var/lib/trutz-mail/openpgp
        if [ -d "${PGP_DIR}" ]; then
            chown -R postfix:postfix "${PGP_DIR}" || true
            chmod 700 "${PGP_DIR}" || true
        fi

        # Restore missing configuration files. dpkg never brings back a
        # deleted conffile on upgrade, and without config.ini every user of
        # this library (mail milters, account handling) fails to start.
        # Only missing files are written, a present file is never touched.
        DEFAULTS_DIR=/usr/share/trutz-py3-lib/defaults
        for f in config.ini comidio_email.pem; do
            if [ ! -e "/etc/comidio/${f}" ] && [ -f "${DEFAULTS_DIR}/${f}" ]; then
                mkdir -p /etc/comidio
                install -m 644 "${DEFAULTS_DIR}/${f}" "/etc/comidio/${f}"
                echo "trutz-py3-lib: /etc/comidio/${f} was missing, restored from ${DEFAULTS_DIR}"
            fi
        done
    ;;

    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