#!/bin/sh

PIDFILE="/var/run/tk103-sms.pid"

{
	. /etc/opengts-tk103/sms.conf
	while :; do
		N=0
		scmxx -d $MODEM_PORT --get --sms -r --slot=unread --out=- | while read GPS_TEXT
		do
			if [ -z "$GPS_TEXT" ]; then N=$(( ($N+1)%2 )); continue; fi
			if [ "$N" = "0" ];
			then
				read GPS_TEXT
				GPS_NUMBER=`echo $GPS_TEXT | grep ": " | cut --delimiter=" " -f2 | sed "s,[^0-9\.],,"`
				read GPS_TEXT
				read GPS_TEXT
				read GPS_TEXT
				read GPS_TEXT
				read GPS_TEXT
				continue;
			fi
			if [ "`echo $GPS_TEXT | cut -c 1-4`" != "lat:" ]; then continue; fi
			GPS_LAT=`echo $GPS_TEXT | grep "lat:" | cut --delimiter=":" -f2 | cut --delimiter=" " -f1 | sed "s,[^0-9\.],,"`
			GPS_LONG=`echo $GPS_TEXT | grep "long:" | cut --delimiter=":" -f3 | cut --delimiter=" " -f1 | sed "s,[^0-9\.],,"`
			GPS_SPEED=`echo $GPS_TEXT | grep "speed:" | cut --delimiter=":" -f4 | sed "s,[^0-9\.],,"`

			read GPS_TEXT
			GPS_TIME=$GPS_TEXT

			read GPS_TEXT

			if [ -n "$GPS_LAT" ] && [ -n "$GPS_LONG" ] && [ -n "$GPS_SPEED" ] && [ -n "$GPS_NUMBER" ]; then echo 'insert into EventData values((select accountID from Device where simPhoneNumber='$GPS_NUMBER'), (select deviceID from Device where simPhoneNumber='$GPS_NUMBER'), UNIX_TIMESTAMP(), 0, '$GPS_LAT', '$GPS_LONG', 0, '$GPS_SPEED', 180, 0, "", 0, "", "", "", 0, 0, 0, "", UNIX_TIMESTAMP());' | mysql -u opengts -popengts -h $MYSQL_SERVER gts; fi

			sleep 1
		done
		sleep 20
	done
} &

echo -n $! > $PIDFILE

exit 0
