#!/bin/bash 

# This script is based on one written Fedor Karpelevitch for "oops"
# to reconfigure the proxy to set the upstream proxy.  I have now
# modified it to also handle "Squid", since I decided to switch
# my local proxy to that instead.

UPSTREAM="$@"

#
# If several proxies are installed we try and deal to all of them
# because it's just too damn much work to figure which one has control!
#

#  The proxies we know how to deal with...
PROXIES="oops squid"
RELOADACTION="force-reload"

modify_conffile() {
  CONFIGURATION="$1"
  shift
  NEWPROXY="$@"
  PROXYCOMMAND="$1"

  if [ "${UPSTREAM}" != "none" ]; then 
    echo "${NEWPROXY}" > ${CONFIGURATION}.N
  fi
  grep -v "^${PROXYCOMMAND} " ${CONFIGURATION} >> ${CONFIGURATION}.N

  mv ${CONFIGURATION}.N ${CONFIGURATION}
}

stopit() {
  echo "Stopping ${PROXY}"
  /etc/init.d/${PROXY} stop
}

startit() {
  echo "Starting ${PROXY}"
  /etc/init.d/${PROXY} start
}

reloadit() {
  echo "Reloading ${PROXY}"
  /etc/init.d/${PROXY} ${RELOADACTION}
}

redirect_oops() {
  echo "Setting OOPS upstream proxy host ($UPSTREAM)" 
  modify_conffile /etc/oops/oops.cfg parent ${UPSTREAM}
}


redirect_squid() {
  PARENT=$1
  TYPE=$2
  # This bit of mucking around lets us handle things in an
  # appropriate way if we just have "setproxy <parent> <port>
  # as we would if we switched from OOPS -> Squid...
  if [ "${TYPE}" = "parent" -o "${TYPE}" = "sibling" ] ; then
    shift
  else
    TYPE=parent
  fi
  PORT=${2:-"3128"}
  ICP_PORT=${3:-"3130"}
  OPTIONS=${4:-"default"}

  echo "Setting Squid upstream proxy host (${PARENT}:${PORT})" 
  modify_conffile /etc/squid/squid.conf cache_peer ${PARENT} ${TYPE} ${PORT} ${ICP_PORT} ${OPTIONS}
}


for PROXY in ${PROXIES} ; do
  if [ -x /usr/sbin/${PROXY} ] ; then
    if [ "$UPSTREAM" = "start" ]; then 
      startit
    elif [ "$UPSTREAM" = "stop" ]; then 
      stopit
    else
      redirect_${PROXY} ${UPSTREAM}
      reloadit
    fi
  fi
done
