#!/bin/sh
insmod ipt_REDIRECT

# There is no Internet yet: we force manual configuration of wan interface
# Redirect all HTTP requests to localhost port 8080
LANIP="$(nvram get lan_ipaddr)"
LANMASK="$(nvram get lan_netmask)"
LANMASK="${LANMASK:-255.255.255.0}"

REDIR1="-s 192.168.182.0/24 -d ! 192.168.182.0/24 -p tcp --dport 80 -j REDIRECT --to-ports 8080"
REDIR2="-s $LANIP/$LANMASK -d ! $LANIP/$LANMASK -p tcp --dport 80 -j REDIRECT --to-ports 8080"

iptables -A INPUT_CFG -j ACCEPT
iptables -t nat -I PREROUTING 1 $REDIR1
iptables -t nat -I PREROUTING 2 $REDIR2

[ -f /var/run/wan_redirect ] && kill "$(cat /var/run/wan_redirect)"
/usr/sbin/httpd -R /cgi-bin/splash.sh -H "$LANIP" -p 8080 -h /www -r OpenWrt
ps ax | grep -E '[h]ttpd.*splash' | awk '{print $1}' > /var/run/wan_redirect

(
	NET=0;
	while [ $NET -eq 0 ]; do 
		# wait for the startup lock to free (happens when hotplug detects an internet connection)
		lock -w /var/run/startup.lock
	
		# Delay to let DSL line synchronize
		ATTEMPT=1;
		nvram set inet=0;
		while [ $ATTEMPT -lt 10 ] && [ $NET -eq 0 ]; do
			# Check wether Internet is ready and by the way, we send MAC address to FON server
			[ -n "$(wget "http://download.fon.com/heartbeat.php" -O-)" ] && NET=1
			ATTEMPT=$(($ATTEMPT + 1))
		done
	
		[ $NET -eq 0 ] && lock /var/run/startup.lock
	done
	
	# If there is Internet connection, we try to syncronize time
	rdate 128.138.140.44
	
	# start a dnsmasq that doesn't give out addresses for the wifi interface
	killall dnsmasq
	[ -f /var/run/wan_redirect ] && {
		kill "$(cat /var/run/wan_redirect)"
		rm -f /var/run/wan_redirect
	}
	
	iptables -F INPUT_CFG
	iptables -t nat -D PREROUTING $REDIR1
	iptables -t nat -D PREROUTING $REDIR2
	
	/etc/init.d/S??dnsmasq start-nowifi
	/etc/init.d/chillispot start
) &
