#!/bin/sh

PATH=$PATH:/bin:/usr/bin
export PATH

# Test page to query
PROXY_TEST='http://www.ams-ix.net/'

# Log file
LOGFILE='/var/log/inet.log'
PIDFILE='/var/run/inet.pid'

# Speed periods
SLEEP_OK='900'
SLEEP_NOK='60'

# Write pid file 
echo $$ > ${PIDFILE}

# Logging
log()
{
	_datestamp=`date "+%Y-%m-%d %H:%M:%S"`
	_msg="[${_datestamp}] $*"
	echo "${_msg}" >> ${LOGFILE}
}

# Start/stop lvrouted
lvrouted()
{
    script=/usr/local/etc/rc.d/lvrouted

    case $1 in

      enable)
        ${script} onestart 
      ;; 

      disable)
        ${script} onestop
      ;;

    esac

}

# Make sure I never die
while [ true ];
do

  # Query the webpage
  fetch -o /dev/null ${PROXY_TEST} > /dev/null 2>/dev/null
  
  # What is the Exit code of fetch?
  EXIT=$?

  # Did the status change?
  if [ "$STATUS" != "$EXIT" ]; then
    STATUS=${EXIT}

    # New status:
    case ${STATUS} in

      # Internet is present, let's enable lvrouted    
      0)
        lvrouted enable
        log "INET OK: Enabled lvrouted"
      ;;

      # Internet is not present, let's disabled lvrouted
      1)
        lvrouted disable
        log "INET CRITICAL: Disabled lvrouted"
      ;;

    esac
  fi

  # Did my magic, lets sleep
  case ${STATUS} in

    # I am in ok state, I will wake up in ...
    0)
      sleep ${SLEEP_OK}
    ;;


    # I am in nok state, I will wake up in ...
    1)
      sleep ${SLEEP_NOK}
    ;;

  esac

 
done