#!/bin/bash

# Copyright Jean-Philippe Guillemin <jp.guillemin@free.fr>. This program is free software;
# you can redistribute it and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm

# Proxyconfig is a simple configurator for system http/ftp proxy

version='1.0'  	# - 07/12/2007 Birth
# Ported to yad (X-only, no gettext) by Claude.

if ! command -v yad >/dev/null 2>&1; then
	echo "yad is required but was not found in PATH." >&2
	exit 1
fi

if [ ! "$DISPLAY" ]; then
	echo "This program requires a running X session." >&2
	exit 1
fi

if [ "$(id -u)" == "0" ]; then
	profilescript="/etc/profile.d/proxy.sh"
else
	profilescript="$HOME/.profile"
fi

touch $profilescript
if [ ! "$(grep "http_proxy" $profilescript)" ] ; then
	echo "# export HTTP proxy variable (added by proxyconfig)" >> $profilescript
	echo "unset http_proxy" >> $profilescript
fi
if [ ! "$(grep "ftp_proxy" $profilescript)" ] ; then
	echo "# export FTP proxy variable (added by proxyconfig)" >> $profilescript
	echo "unset ftp_proxy" >> $profilescript
fi

# Path needs to be extended in case you're only half a root :)
export PATH="${PATH}:/usr/sbin:/sbin"

###############################################
# Set Proxy

currenthttpproxy=$(sed -n "s/^.*[ \t]*http_proxy='*\(http:\/\/\)*\([^']*\)'*/\2/p" $profilescript)
currentftpproxy=$(sed -n "s/^.*[ \t]*ftp_proxy='*\(ftp:\/\/\)*\([^']*\)'*/\2/p" $profilescript)

result=$(yad --center --width=480 \
	--title "Proxy Configuration (boot parameter)" \
	--text "HTTP and FTP proxies:\n(user:pass@IPPROXY:PORT)" \
	--form --columns=1 \
	--field="HTTP proxy" "$currenthttpproxy" \
	--field="FTP proxy" "$currentftpproxy" \
	--button="OK:0")

newhttpproxy="$(echo "$result" | cut -d'|' -f1)"
newftpproxy="$(echo "$result" | cut -d'|' -f2)"

[ ! "$newftpproxy" ] && newftpproxy="$newhttpproxy"

# save parameters
if [ "$newhttpproxy" ]; then
	sed -i "s|^.*http_proxy.*$|export http_proxy=http://$newhttpproxy|" $profilescript
	sed -i "s|^.*ftp_proxy.*$|export ftp_proxy=ftp://$newftpproxy|" $profilescript
else
	sed -i "s|^.*http_proxy.*$|unset http_proxy|" $profilescript
	sed -i "s|^.*ftp_proxy.*$|unset ftp_proxy|" $profilescript
fi

# end
