#!/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


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
