#!/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.
# 
# Rick van der Zwet <info@rickvanderzwet.nl>
#

TAG=`basename $0`
INET_STATUS=down
service lvrouted onestatus > /dev/null && LVROUTED_STATUS="running" || LVROUTED_STATUS="stopped"

# Main I-net check
fetch -o /dev/null -q http://proxy-test.wirelessleiden.nl && INET_STATUS=up

if [ $INET_STATUS = "down" ]; then
  # Failback internet check
  fetch -o /dev/null 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
