#!/bin/sh 

INITSCRIPT=/etc/rc1.d/S40chillispot
DAEMON=chilli
PID_LOOP_F=/var/run/chilli_loop.pid
PID_F=/var/run/chilli.pid
PARSECAD=fon.com/login/gateway
LOOP=true
CHILLIPORT=3990 
DELAY=86400
SECONDS=0
DELAY2=20
SECONDS2=0

pid_test() {
	PID=$(pidof $DAEMON)
	if [ -z "$PID" ]; then
		# no pid, daemon is dead
		return 1
	fi
}

redirection_test () {
	IP=$(ifconfig tun0 | grep 'inet addr' | awk '{print $2}' | cut -d':' -f2)
	[ -z "$IP" ] && return 1

	wget http://$IP:$CHILLIPORT 2> /tmp/wget.out

	grep -q $PARSECAD /tmp/wget.out
	[ $? == 1 ] && return 1

	return 0
}

# monitoring loop.
loop() {
	#trap quit SIGINT SIGTERM SIGHUP SIGKILL
	while [ $LOOP = "true" ] ; do
		sleep 1
		SECONDS=$(expr $SECONDS + 1)
		if [ "$SECONDS" = "$DELAY" ]; then
			$INITSCRIPT reload
		fi
		SECONDS2=$(expr $SECONDS2 + 1)
		if [ "$SECONDS2" = "$DELAY2" ]; then
			SECONDS2=0
			pid_test
			[ $? == 1 ] && $INITSCRIPT restart && continue
			redirection_test
			[ $? == 1 ] && $INITSCRIPT restart && continue
		fi
	done

	exit 0
}

loop 
