#!/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 <info@rickvanderzwet.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="yes"
control_tinyproxy="yes"
(( checkyesno service_ileiden || checkyesno service_proxy ) && checkyesno lvouted_enable ) || control_lvrouted="no"
(( checkyesno service_ileiden || checkyesno service_proxy ) && checkyesno tinyproxy_enable ) || control_tinyproxy="no"


service lvrouted onestatus > /dev/null && LVROUTED_STATUS="running" || LVROUTED_STATUS="stopped"
service tinyproxy onestatus > /dev/null && TINYPROXY_STATUS="running" || TINYPROXY_STATUS="stopped"

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

# Get connection stats for internet
INET_STATUS=up && check_http http://proxy-test.wirelessleiden.nl || check_http http://ams-ix.net || INET_STATUS=down
# Connections statistics for proxy
export HTTP_PROXY=${HTTP_PROXY-:http://proxy.wleiden.net:3128}
PROXY_STATUS=up && 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
echo proxy=$PROXY_STATUS
EOF

# Control connections
if checkyesno 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 checkyesno control_tinyproxy; then
  if [ $TINYPROXY_STATUS_STATUS = "stopped" ] && [ $INET_STATUS = "up" ]; then
    service tinyproxy start | logit
  elif [ $TINYPROXY_STATUS = "running" ] && [ $INET_STATUS = "down" ]; then
    service tinyproxy stop | logit
  fi
fi
