#!/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 GTK/NCURSES configurator for system http/ftp proxy


version='1.0'  	# - 07/12/2007 Birth


# Take a look at "Xdialog" and use it instead of "dialog" in case X is running
if [[ "$DISPLAY" && "$(which Xdialog 2>&1 | grep -v "which: no")" ]]; then
	dialog="Xdialog --wrap --left --icon proxy"
	shortttl='3000'
	longttl='8000'
	xflag='yes'
else
	dialog="dialog"
	shortttl=''
	longttl=''
	xflag='no'
fi

# Translations only work with utf8 locales
if [ ! `echo $LANG | grep -i utf` ]; then
	LANG=en_US
fi

# Gettext internationalization
export TEXTDOMAIN="proxyconfig"
export TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh

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

# The profile script
profilescript='/etc/profile.d/proxy.sh'
touch $profilescript

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

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

if [ ! "$dialog" = "dialog" ]; then
newvalue="$($dialog --stdout --title "$(eval_gettext 'Proxy Configuration (boot parameter)')" --no-cancel --2inputsbox "$(eval_gettext 'HTTP and FTP proxies') :\n($(eval_gettext 'user'):pass@IPPROXY:PORT)  " 16 70 \
"$(eval_gettext 'HTTP proxy')" "$currenthttpproxy" \
"$(eval_gettext 'FTP proxy')" "$currentftpproxy")"
  newhttpproxy="$(echo $newvalue | cut -d / -f 1 )"
  newftpproxy="$(echo $newvalue | cut -d / -f 2 )"
else
  newhttpproxy="$($dialog --stdout --title "$(eval_gettext 'HTTP proxy')" --no-cancel --inputbox "$(eval_gettext 'Enter the HTTP proxy') ($(eval_gettext 'user'):pass@IPPROXY:PORT) :" 11 75 "$currenthttpproxy")"
  newftpproxy="$($dialog --stdout --title "$(eval_gettext 'FTP proxy')" --no-cancel --inputbox "$(eval_gettext 'Enter the FTP proxy') ($(eval_gettext 'user'):pass@IPPROXY:PORT) :" 11 75 "$currentftpproxy")"
fi

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

# save parameters
if [ "$newhttpproxy" ]; then
  echo "export http_proxy='http://$newhttpproxy'" > $profilescript
  echo "export ftp_proxy='ftp://$newftpproxy'" >> $profilescript
  chmod 755 $profilescript
else
  echo "unset http_proxy" > $profilescript
  echo "unset ftp_proxy" >> $profilescript
  chmod 755 $profilescript
fi


# end
