#! /bin/sh

NAME=apt-proxy
APTPROXY_USER=aptproxy
APTPROXY_LOGFILE=/var/log/$NAME.log
CACHEDIR=/var/cache/apt-proxy

. /usr/share/debconf/confmodule
db_version 2.0

set -e
case "$1" in
    configure)
        # Check if the user exist and do what is needed
        if ! id $APTPROXY_USER > /dev/null 2>&1; then
            # Create user
            echo creating $APTPROXY_USER user...
            adduser --quiet --system --ingroup nogroup \
                --home $CACHEDIR --no-create-home $APTPROXY_USER
        fi

        # Make apt-proxy user own cache directory
        chown -R $APTPROXY_USER $CACHEDIR
        # Create a blank logfile owned by apt-proxy user
        touch $APTPROXY_LOGFILE
        chown $APTPROXY_USER:adm $APTPROXY_LOGFILE
        chmod 640 $APTPROXY_LOGFILE

        PREV="$2"
        db_fget $NAME/upgrading-v2 had_v2_conf || true
        had_v2_conf=$RET

        if dpkg --compare-versions "$PREV"  lt-nl 1.9; then
            if [ -x /usr/sbin/update-inetd ]; then
              echo "Disabling inetd's apt-proxy v1 line."
              update-inetd --comment-chars "#<apt-proxy-v2># " --disable 9999
            fi
            db_fset $NAME/upgrading-v2 seen false || true
            db_input medium $NAME/upgrading-v2 || true
            db_go
        fi
        if
            dpkg --compare-versions "$PREV"  lt-nl 1.9 && ( ! $had_v2_conf ) \
            && [ -r /etc/apt-proxy/apt-proxy.conf ]
        then
            echo Customising configuration file based on old settings.
            cp -a --backup=numbered /etc/apt-proxy/apt-proxy-v2.conf \
                        /etc/apt-proxy/apt-proxy-v2.conf.backup
            OUTPUT=$(/usr/sbin/apt-proxy-v1tov2 /etc/apt-proxy/apt-proxy.conf \
                                        /etc/apt-proxy/apt-proxy-v2.conf.backup\
                                        2>&1 \
                                        > /etc/apt-proxy/apt-proxy-v2.conf )
            echo "$OUTPUT" > /var/log/apt-proxy-v1tov2.log
            chown aptproxy:adm /var/log/apt-proxy-v1tov2.log
            chmod 640 /var/log/apt-proxy-v1tov2.log
            echo "The log of conversion was save in /var/log/apt-proxy-v1tov2.log."
            if [ -n "$OUTPUT" ]; then
                db_fset $NAME/upgrading-v2-result seen false
                db_input high $NAME/upgrading-v2-result || true
                db_go
            fi
        fi
        # Older versions got database permissions wrong #288829
        if dpkg --compare-versions "$PREV" lt-nl 1.9.27; then
            if [ -d /var/cache/apt-proxy/.apt-proxy ]; then
                echo "Fixing database owner."
                chown -R aptproxy.nogroup /var/cache/apt-proxy/.apt-proxy
            fi
        fi
        ;;
    abort-upgrade|abort-remove|abort-deconfigure)
        ;;
    *)
        echo "postinst called with unknown argument \`$1'" >&2
        ;;
esac

db_stop

#DEBHELPER#

exit 0
