#!/bin/sh -
#
# An normal proxy should not have an defaultrouter configured, as all calls to
# the outside world are handled via PF redirects.
#
# Rick van der Zwet <rick@wirelessleiden.nl>

. /etc/rc.subr

: ${service_proxy_normal="NO"}
: ${service_proxy_ileiden="NO"}
: ${service_accesspoint="NO"}

load_rc_config 'ileiden'

update_pf_conf() {
  $LOGGER "reason: $reason"
  if is_default_interface 2>/dev/null; then
    $LOGGER "is_default_interface: TRUE"
    new_ext_if_gw=`route -n get default 2>/dev/null | awk '/gateway/ {print $2}'`
    $LOGGER "prev default gateway: $ext_if_gw"
    $LOGGER "curr default gateway: $new_ext_if_gw"
    if [ -n "$new_ext_if_gw" -a "$new_ext_if_gw" != "$ext_if_gw" ];  then
      $LOGGER "Syncing new default route ($new_ext_if_gw) to routing table 1"
      { grep -v '^ext_if_gw=' $rc_conf_running; echo "ext_if_gw=$new_ext_if_gw"; } > $rc_conf_running
      $LOGGER "`setfib 1 route -q del default 2>&1`"
      $LOGGER "`setfib 1 route -q add default $new_ext_if_gw 2>&1`"
    fi
  else
    $LOGGER "is_default_interface: FALSE"
  fi

  # Make sure not to nuke the default route on an ileiden proxy,
  # as it will rendering it usefull
  checkyesno "service_proxy_ileiden" && return

  if [ -n "$new_ext_if_gw" ] && checkyesno "service_proxy_normal" && checkyesno "service_accesspoint"; then
    $LOGGER "Removing default route from routing table 0 as machine is marked as service_proxy AND service_accesspoint"
    $LOGGER "`route -q del default 2>&1`"
  fi
}

reason=${reason:-${REASON:-"BOUND"}}
case $reason in
  BOUND|RENEW|REBIND|REBOOT)
    update_pf_conf
    ;;
  TIMEOUT)
    update_pf_conf 
    ;;
esac
  
