#!/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`
INET_STATUS=down
service lvrouted onestatus > /dev/null && LVROUTED_STATUS="running" || LVROUTED_STATUS="stopped"

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

# Main I-net check
check_http http://proxy-test.wirelessleiden.nl && INET_STATUS=up

if [ $INET_STATUS = "down" ]; then
  # Failback internet check
  check_http http://ams-ix.net && INET_STATUS=up
fi

if [ $LVROUTED_STATUS = "stopped" ] && [ $INET_STATUS = "up" ]; then
  service lvrouted start | logger -t "$TAG"
elif [ $LVROUTED_STATUS = "running" ] && [ $INET_STATUS = "down" ]; then
  service lvrouted stop | logger -t "$TAG"
fi

# Retrieve proxy status
export HTTP_PROXY=${HTTP_PROXY-:http://proxy.wleiden.net:3128}
PROXY_STATUS=down
check_http http://proxy-test.wirelessleiden.nl && PROXY_STATUS=down

if [ $INET_STATUS = "down" ]; then
  # Failback internet check
  check_http http://ams-ix.net && PROXY_STATUS=up
fi

echo -e "internet=$INET_STATUS\nproxy=$PROXY_STATUS" > /tmp/network.status
