#!/bin/sh
#
# Pen proxy wrapper, periodic check for best connections available.
#
# Stichting Wireless Leiden
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#

BIND_ADDR=${1:-172.31.255.1:3128}


# Internal parameters, don't touch unless you know what you are doing.
TEST_URL="http://tinyproxy.stats/"
TEST_INTERVAL=`expr 15 \* 60`
PIDFILE='/var/run/pen.pid'
PEN='/usr/local/bin/pen'
PEN_FLAGS="-S 20 -b 30 -p ${PIDFILE} ${BIND_ADDR}:${BIND_PORT}"

TAG=`basename $0`
logit() {
  logger -t "$TAG" $*
}

update_proxy_list() {
  # Get (updated) proxy listing from configuration files.
  . /etc/rc.subr
  load_rc_config "pen_wrapper"
  make_list "$list_normal_proxies" " "
}


# Return speed value, higher is better
test_proxy() {
  PROXY=$1
  retstr=`HTTP_PROXY=http://$PROXY fetch -T 3 -o /dev/null ${TEST_URL} 2>&1` || return 0
  BPS=`echo "${retstr}" | awk '/Bps/ {printf $4}'`
  return $BPS
}

# Sort proxy list on highest bandwidth
sort_proxies() {
  result=''
  for host in $*; do
    bps=`test_proxy $host:3128`
    result="$bps $host:3128"
  done

  echo $result | xargs -n2 | sort -r | awk '{print $2}' | xargs
}


##
# Main loop
LIVE_PROXY_LIST=''
while true; do
  PROXY_LIST=`update_proxy_list`
  if [ -z "$PROXY_LIST" ]; then
    logit "Not starting: list_normal_proxies variable not configured"
  else
    NEW_PROXY_LIST=`sort_proxies $PROXY_LIST`
    if [ "${LIVE_PROXY_LIST}" != "${NEW_PROXY_LIST}" ]; then
      logit "INFO: New listing to be configured '${NEW_PROXY_LIST}'"

      # Pen should only be started if alias exists
      ifconfig | grep -q ${BIND_ADDR} || {
        logit "Not starting: alias $BIND_ADDR not configured!"
      } && {
        [ -r ${PIDFILE} ] && kill `cat ${PIDFILE}`
        ${PEN} ${PEN_FLAGS} ${NEW_PROXY_LIST}
        LIVE_PROXY_LIST="${NEW_PROXY_LIST}"
      }
    fi
  fi

  sleep ${TEST_INTERVAL}
done
