#!/bin/sh
set -e

# Source debconf library.
. /usr/share/debconf/confmodule

disable-https-apt

db_get apt-cacher-ng-client/apt-proxy-ip
APTPROXYIP="$RET"

    if [ "$APTPROXYIP" != "" ]; then

HOSTSBACKUPDIR="/var/cache/apt-cacher-ng-client"
if [ ! -d $HOSTSBACKUPDIR ];then
	mkdir -pv $HOSTSBACKUPDIR
fi
cp -vp /etc/hosts $HOSTSBACKUPDIR/`date +%Y%m%d-%H%M%S`.hosts.backup

# clear old entry
sed -i '/# apt-proxy entry added by apt-cacher-ng-client/d' /etc/hosts

grep -E "([0-9]{1,3}\.){3}[0-9]{1,3} apt-proxy" /etc/hosts| while read I
do
	sed -i "/$I/d" /etc/hosts
done
# for IP has multi hostnames,only clear apt-proxy hostname
sed -i "s/apt-proxy//" /etc/hosts

# write new entry
	echo "# apt-proxy entry added by apt-cacher-ng-client" >> /etc/hosts
	echo "$APTPROXYIP apt-proxy" >> /etc/hosts
    fi

#DEBHELPER#
