#!/bin/sh
#
# Set up global proxy used using the WPAD URL specified on the command
# line, or if it is empty the wpad DNS alias.  If no WPAD file is
# found, disable the use of a proxy.

set -e

log() {
    logger -t update-proxy-from-wpad "$@"
}

error() {
    if [ -t 1 ] ; then # Only print errors when stdout is a tty
	echo "error: $@"
    fi
    logger -t update-proxy-from-wpad "error: $@"
}

append_if_missing() {
    file="$1"
    string="$2"
    if [ -e "$file" ] ; then
	if ! grep -qxF "$string" "$file" ; then
	    log "Appending '$string' to $file."
	    echo "$string" >> $file
	fi
    fi
}

# Make sure to fetch the wpad file without proxy settings, to behave
# like browsers who need to get their proxy settings without using a
# proxy.
http_proxy=
ftp_proxy=

# Use http://wpad/wpad.dat configuration to update /etc/environment
# and apt configuration if possible
wpadurl="$1"
if [ -z "$wpadurl" ] &&
   wget -nv -T 10 -O /dev/null http://wpad/wpad.dat >/dev/null 2>&1; then
    wpadurl="http://wpad/wpad.dat"
fi

if [ "$wpadurl" ] ; then
    eval `/usr/share/debian-edu-config/tools/wpad-extract $wpadurl`
fi

# Update /etc/environment with the current proxy settings extracted
# from the WPAD file
file=/etc/environment
touch $file
chmod a+r $file
sed -e "s%^http_proxy=.*%http_proxy=$http_proxy%" \
    -e "s%^ftp_proxy=.*%ftp_proxy=$http_proxy%" \
    < $file > $file.new && chmod a+r $file.new

# Only replace if new file have content and is different from the old
# file
if [ ! -s $file.new ] || cmp -s $file.new $file ; then
    rm $file.new
else
    mv $file.new $file
fi
append_if_missing $file http_proxy=$http_proxy
append_if_missing $file ftp_proxy=$ftp_proxy

# Make sure APT used from cron also get the wanted proxy settings
# /etc/apt/apt.conf is created by debian-installer if a proxy was used
# during installation, so we update this file.
file=/etc/apt/apt.conf
touch $file
chmod a+r $file
sed -e "s%^Acquire::http::Proxy .*%Acquire::http::Proxy \"$http_proxy\";%" \
    -e "s%^Acquire::ftp::Proxy .*%Acquire::ftp::Proxy \"$ftp_proxy\";%" \
    < $file > $file.new && chmod a+r $file.new

# Only replace if new file have content and is different from the old
# file
if [ ! -s $file.new ] || cmp -s $file.new $file ; then
    rm $file.new
else
    mv $file.new $file
fi
append_if_missing $file "Acquire::http::Proxy \"$http_proxy\";"
append_if_missing $file "Acquire::ftp::Proxy \"$ftp_proxy\";"
