#!/bin/sh

set -e

action=$1

PREFERENCES=/etc/apt/listchanges.conf

if [ "$action" = "configure" ]; then
    version=$2
    # Source debconf library.
    . /usr/share/debconf/confmodule

    echo "[apt]" > $PREFERENCES.new

    db_get apt-listchanges/frontend
    echo "frontend=$RET" >> $PREFERENCES.new

    db_get apt-listchanges/email-address
    echo "email_address=$RET" >> $PREFERENCES.new

    db_get apt-listchanges/confirm
    if [ "$RET" = "true" ]; then
        echo "confirm=1" >> $PREFERENCES.new
    else
        echo "confirm=0" >> $PREFERENCES.new
    fi

    db_get apt-listchanges/save-seen
    if [ "$RET" = "true" ]; then
        echo "save_seen=/var/lib/apt/listchanges.db" >> $PREFERENCES.new
    fi

    db_get apt-listchanges/which
    echo "which=$RET" >> $PREFERENCES.new

    ucf --debconf-ok $PREFERENCES.new $PREFERENCES
    rm -f $PREFERENCES.new

    ## Cleanup from older versions

    # Remove config files from older versions (pre-1.14)
    rm -f /etc/apt-listchanges.conf /etc/apt-listchanges.conf.old

    # We used to add ourselves to apt.conf (pre-1.34); remove ourselves
    if dpkg --compare-versions "$version" lt 1.34 \
	&& test -e /etc/apt/apt.conf; then
	cp /etc/apt/apt.conf /etc/apt/apt.conf.old

	(grep -v apt-listchanges /etc/apt/apt.conf.old \
	    > /etc/apt/apt.conf) || true

	rm -f /etc/apt/apt.conf.old

	if [ ! -s /etc/apt/apt.conf ]; then
	    rm -f /etc/apt/apt.conf
	    rmdir --ignore-fail-on-non-empty -p /etc/apt/
	fi
    fi

    # Config file rename (pre-1.56)
    OLDAPTCONFIG=/etc/apt/apt.conf.d/20-apt-listchanges.conf
    NEWAPTCONFIG=/etc/apt/apt.conf.d/20listchanges
    if dpkg --compare-versions "$version" lt 1.56 \
	&& test -f "$OLDAPTCONFIG"; then
	if ! cmp --silent "$OLDAPTCONFIG" "$NEWAPTCONFIG"; then
	  cp "$OLDAPTCONFIG" "$NEWAPTCONFIG"
        fi
	rm -f "$OLDAPTCONFIG"
    fi

    # Re-create database (pre-2.0)
    if dpkg --compare-versions "$version" lt 2.1; then
        rm -f /var/lib/apt/listchanges.db
    fi
fi

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
