# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

function set_proxy() {
    if [ -f /etc/uproxy.conf ]; then
        source /etc/uproxy.conf
    elif [ -z "$http_proxy" -o "$1" == "-f" ]; then
        local proxy
        local ENABLE_AUTO_PROXY
        local PROXY_LOGIN PROXY_PASSWORD
        local HTTP_PROXY_HOST HTTP_PROXY_PORT
        local FTP_PROXY_HOST FTP_PROXY_PORT
        local PROXY_LOCAL_DOMAINS AUTHFTP_PROXY_HOST

        local default_profile
        if [ -f "$HOME/etc/default.${HOSTNAME%%.*}/proxy" ]; then
            default_profile="$HOME/etc/default.${HOSTNAME%%.*}/proxy"
        elif [ -f "$HOME/etc/default/proxy" ]; then
            default_profile="$HOME/etc/default/proxy"
        fi
        [ -f "$default_profile" ] && source "$default_profile"

        if [ -n "$PROXY_ENABLE_LIBPROXY" -a -x /usr/bin/proxy ]; then
            local -a proxies=($(/usr/bin/proxy <<<http://www.google.fr/ 2>/dev/null))
            proxy="${proxies[0]}"
            if [ "$proxy" == "direct://" ]; then
                # pas de proxy
                unset http_proxy
                unset ftp_proxy
                unset no_proxy
                return
            elif [[ "$proxy" == http://127.0.0.1:* ]]; then
                # proxy de self-network
                export http_proxy="$proxy"
                export ftp_proxy="$proxy"
                unset no_proxy
                return
            fi
            unset no_proxy
        elif [ -f "$default_profile" ]; then
            # proxy par défaut
            if [ -n "$HTTP_PROXY_HOST" ]; then
                proxy="http://$HTTP_PROXY_HOST:${HTTP_PROXY_PORT:-3128}/"
            fi

            export no_proxy=
            local local_domain
            for local_domain in "${PROXY_LOCAL_DOMAINS[@]}"; do
                no_proxy="${no_proxy:+$no_proxy,}$local_domain"
            done
            [ -n "$no_proxy" ] || unset no_proxy
        fi

        if [ -n "$proxy" ]; then
            if [ -n "$PROXY_LOGIN" ]; then
                proxy="${proxy/http:\/\//http://${PROXY_LOGIN}${PROXY_PASSWORD:+:$PROXY_PASSWORD}@}"
            fi
            export http_proxy="$proxy"
            export ftp_proxy="$proxy"
        else
            unset http_proxy
            unset ftp_proxy
        fi
    fi
}
set_proxy
