#!/bin/bash
# this script is started once per day in the remote RPi1 192.168.100.120 at mokki having mobile data 
# this script communicates with the script shutdown.sh through file in /tmp/
gprs=0
hspa=0
array_ind=0
array_max=3
ip_array=(www.ubuntu-fi.org 8.8.8.8 www.fmi.fi)
SECONDS=0
while [ $SECONDS -lt 300 ]
do
	if [ $gprs -lt 3 ]; then
#		wvdial GPRS 2>>/tmp/wvdial.mess &
		wvdial GPRS &
		sleep 50s
		gprs=$[$gprs+1]
		array_ind=0
	else
		if [ $hspa -lt 3 ]; then
			wvdial HSPA &
			sleep 50s
			hspa=$[$hspa+1]
			array_ind=0
		else
			break
		fi
	fi
	if ps -C wvdial|grep wvdial; then
		while [ $array_ind -lt $array_max ]
		do
			ping -qc 1 ${ip_array[$array_ind]}
			if [ $? -eq 0 ]; then
				/usr/bin/python /home/mokki/udp-rpi1.py "$gprs" &
				sleep 20s
				break 2
			else
				array_ind=$[$array_ind+1]
			fi
			sleep 1s
		done
	fi
	killall wvdial
	killall pppd
	sleep 10s
done
killall wvdial
killall pppd
touch /tmp/shutdown.txt										# script shuts down RPi1, later the timer switches off 230 V power
exit 0
