#!/bin/sh /etc/rc.common

RETRY_TO_RL1=1
RETRY_TO_RL2=300

disable() {
	name="$(basename "${initscript}")"
	rm -f "$IPKG_INSTROOT"/etc/rc.d/S??$name
	rm -f "$IPKG_INSTROOT"/etc/rc1.d/S??$name
	rm -f "$IPKG_INSTROOT"/etc/rc2.d/K??$name
	rm -f "$IPKG_INSTROOT"/etc/rc2.d/S??$name
}

enable() {
	name="$(basename "${initscript}")"
	disable
	ln -s "/etc/init.d/$name" "$IPKG_INSTROOT/etc/rc.d/S${START}${name##S[0-9][0-9]}"
	ln -s "/etc/init.d/$name" "$IPKG_INSTROOT/etc/rc1.d/S99${name##S[0-9][0-9]}"
	ln -s "/etc/init.d/$name" "$IPKG_INSTROOT/etc/rc2.d/K15${name##S[0-9][0-9]}"
	ln -s "/etc/init.d/$name" "$IPKG_INSTROOT/etc/rc2.d/S99${name##S[0-9][0-9]}"
}

change_runlevel_1 () {
	# Test to change from runlevel S/2 to runlevel 1. If fon.com fails try google.com, 
	# if fails tries again in RETRY_TO_RL1 seconds. Changes to runlevel 1 if either of them is online.
	while [ -z "$(/usr/bin/wget "http://download.fon.com/heartbeat.php" -O-  2> /dev/null)" ]; do
		[ -n "$(/usr/bin/wget "http://www.google.com" -O-  2> /dev/null)" ] && break
		sleep $RETRY_TO_RL1
	done

	/sbin/fs -l 1
}

change_runlevel_2 () {
	# Test connectivity with fon.com every RETRY_TO_RL1 seconds, if fails tries connectivity with	
	# google.com, every RETRY_TO_RL2 seconds, if fails goes to runlevel 2 (off line runlevel).
	while [ -n  "$(/usr/bin/wget "http://download.fon.com/heartbeat.php" -O-  2> /dev/null)" ]; do
		sleep $RETRY_TO_RL2
	done

	while [ -n  "$(/usr/bin/wget "http://www.goole.com" -O-  2> /dev/null)" ]; do
		sleep $RETRY_TO_RL2
	done

	/sbin/fs -l 2
}

START=99
start() {
	[ "$(fs -s)" = 2 ] && {
		# reapply basic networking/wifi settings
		export wifi_run=1
		ifup lan
		/etc/init.d/mgmtnetwork start
		wifi
		killall pppd 2>/dev/null >/dev/null
		killall udhcpc 2>/dev/null >/dev/null
		rm -f /tmp/resolv.conf.auto
		ifup wan
		/etc/init.d/firewall start
		/etc/init.d/forwardports start
		/etc/init.d/redirect start
	}
	(
		if [ "$(fs -s)" = 1 ]; then
			change_runlevel_2
		else
			change_runlevel_1
		fi
	) &
}

boot() {
	if [ `uci get fon.wan.mode` = "pppoe" ]; then ifup wan; fi
	start
}

stop() {
        killall S99conncheck
        killall wget
}

