#!/bin/sh
#
# gwck wait_default module
#
# Copyright (C) 2008-2013 Simó Albert i Beltran
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

#############
# Variables #
#############

# Seconds between tests.
GWCK_MOD_WAIT_DEFAULT_TIME="${GWCK_MOD_WAIT_DEFAULT_TIME:-30}"

# IP version.
GWCK_MOD_WAIT_DEFAULT_IPV="${GWCK_MOD_WAIT_DEFAULT_IPV:-4}"

# The filter to select the route.
GWCK_MOD_WAIT_DEFAULT_FILTER_SELECT_ROUTE="${GWCK_MOD_WAIT_DEFAULT_FILTER_SELECT_ROUTE:-^default\b}"

# The filter to ignore routes.
GWCK_MOD_WAIT_DEFAULT_FILTER_IGNORE_ROUTES="${GWCK_MOD_WAIT_DEFAULT_FILTER_IGNORE_ROUTES:-\bdev \(bmx6_out\|x6\)}"

#############
# Functions #
#############

gwck_mod_wait_default()
{
	log "Waiting default gateway"

	local detected_default_gateway=false

	while ! $detected_default_gateway
	do
		if ip -"$GWCK_MOD_WAIT_DEFAULT_IPV" route | grep -v "$GWCK_MOD_SPECIFIC_ROUTES_FILTER_IGNORE_ROUTES" | grep -q "$GWCK_MOD_WAIT_DEFAULT_FILTER_SELECT_ROUTE"
		then
			log "Direct default gateway detected."
			detected_default_gateway="true"
		else
			if $detected_default_gateway
			then
				log "Direct default gateway not detected."
				detected_default_gateway="false"
				! $LOOP && exit
			fi
			sleep $GWCK_MOD_WAIT_DEFAULT_TIME
		fi
	done
}

##############
# gwck hooks #
##############

gwck_mod_wait_default_init()
{
	gwck_mod_wait_default
}

#gwck_mod_wait_default_connect()
#{
#	:
#}

#gwck_mod_wait_default_disconnect()
#{
#	:
#}

#gwck_mod_wait_default_term()
#{
#	:
#}


#############
# Main code #
#############

# Actions in run-time load module.
:
