#!/bin/sh
#
# Internet Connection Wrapper From Cron
#
# a) Disable lvrouted if the internet is down.
# b) Re-enable lvrouted if the internet is back up.
#
# XXX: Do we need build an fail-save for flapping states?
# XXX: Do we need to manage state, like DHCP here?
# XXX: Check if page output is actually the output expected and not some weird captive portal somewhere.
# XXX: For effiently reasons this should be combined with the nagios check_inet check
# 
# Rick van der Zwet <rick@wirelessleiden.nl>
#

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

# Check if we need to check inet at all
. /etc/rc.subr

load_rc_config "lvrouted"
load_rc_config "tinyproxy"

: ${lvouted_enable="NO"}
: ${tinyproxy_enable="NO"}
: ${service_ileiden="NO"}
: ${service_proxy="NO"}

control_lvrouted=false
control_tinyproxy=false
checkyesno service_proxy_ileiden && checkyesno lvouted_enable control_lvrouted=true
checkyesno service_proxy_normal && checkyesno tinyproxy_enable || control_tinyproxy=false


# Get current state of the daemons
lvouted_status="stopped"
tinyproxy_status="stopped"
service lvrouted onestatus > /dev/null && lvouted_status="running"
service tinyproxy onestatus > /dev/null && tinyproxy_status="running"

check_http() {
 fetch -o /dev/null -q $* 2>/dev/null
}

# Get connection stats for internet direct and via proxy
inet_status=up
proxy_status=up
check_http http://proxy-test.wirelessleiden.nl || check_http http://ams-ix.net || inet_status=down
export HTTP_PROXY=${HTTP_PROXY-:http://proxy.wleiden.net:3128}
check_http http://tinyproxy.stats || check_http http://ams-ix.net || proxy_status=down

# Log Network Status
cat <<EOF > /tmp/network.status
internet=$inet_status
proxy=$proxy_status
EOF

# Control connections
if $control_lvrouted; then
  if [ $lvrouted_status = "stopped" ] && [ $inet_status = "up" ]; then
    service lvrouted start | logit
  elif [ $lvrouted_status = "running" ] && [ $inet_status = "down" ]; then
    service lvrouted stop | logit
  fi
fi

if $control_tinyproxy; then
  if [ $tinyproxy_status = "stopped" ] && [ $inet_status = "up" ]; then
    service tinyproxy start | logit
  elif [ $tinyproxy_status = "running" ] && [ $inet_status = "down" ]; then
    service tinyproxy stop | logit
  fi
fi
