#!/bin/sh
#
# Set up global proxy used using the WPAD URL found using the 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
}

# Update /etc/environment with the current proxy settings extracted
# from the WPAD file
update_etc_environment() {
    file=/etc/environment
    touch $file
    chmod a+r $file
    sed -e "s%^http_proxy=.*%http_proxy=$http_proxy%" \
	-e "s%^ftp_proxy=.*%ftp_proxy=$ftp_proxy%" \
	-e "s%^https_proxy=.*%https_proxy=$https_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
    append_if_missing $file https_proxy=$https_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.
update_apt_conf() {
    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\";%" \
	-e "s%^Acquire::https::Proxy .*%Acquire::https::Proxy \"$https_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\";"
    append_if_missing $file "Acquire::ftp::Proxy \"$https_proxy\";"
}

if [ -r /etc/debian-edu/config ] ; then
    . /etc/debian-edu/config
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=

eval `/usr/share/debian-edu-config/tools/wpad-extract`
ftp_proxy=$http_proxy
https_proxy=$http_proxy

update_apt_conf

# Do not set proxy in /etc/environment for machines that move around,
# as the value will be wrong when arriving at a new network.
if echo "$PROFILE" | egrep -q 'Roaming-Workstation|Standalone' ; then
    :
else
    update_etc_environment
fi
