#!/bin/sh
#
# swia - Scan where I am
#
# Copyright (C) 2012 Simó Albert i Beltran
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
# This tool scans wireless networks and uses the Google Location Services
# to get the geolocation.
# http://code.google.com/intl/en/apis/gears/geolocation_network_protocol.html
#

echo "Google Location Services are discontinued." 1>&2
exit 1

# URL of Google Location Services.
GLS_URL="http://www.google.com/loc/json"

# JSON data to be posted.
post_data="$(
iwlist scanning 2> /dev/null | \
awk '
function print_cell()
{
	if (mac_address || essid || channel || quality || noise) print "{"
	if (mac_address)
	{
		print "\"mac_address\":\"" mac_address "\"";
		if (essid || channel || quality || noise) print ",";
	}
	if (essid)
	{
		print "\"ssid\":" essid;
		if (channel || quality || noise) print ",";
	}
	if (channel)
	{
		print "\"channel\":\"" channel "\"";
		if (quality || noise) print ",";
	}
	if (quality)
	{
		print "\"signal_strength\":\"" quality "\"";
		if (noise) print ",";
	}
	if (noise) print "\"signal_to_noise\":\"" noise "\"";
	if (mac_address || essid || channel || quality || noise) print "}"
}
BEGIN {
	ORS="";
	print "{\"host\":\"maps.google.com\",\"version\":\"1.1.0\",\"wifi_towers\":["
}
/\<Cell/ {
	# new cell description has started, so we need to print previous one.
	print_cell()
	if (mac_address || essid || channel || quality || noise) print ","
	essid="";
	channel="";
	quality="";
	noise="";
	mac_address=$5;
}
/\<ESSID:/ {
	FS=":";
	essid=$2;
	FS=" ";
}
/\<Quality/ {
	FS="[= ]+";
	quality=$6;
	noise=$10;
	FS=" ";
}
/\<Channel:/ {
	FS=":";
	channel=$2;
	FS=" ";
}
/\<Frequency:/ {
	FS="[ )]+";
	channel=$5;
	FS=" ";
}
END {
	# handle last cell
	print_cell()
	print "]}"
}')"


# Get the geolocation from Google Location Services.
geolocation_json="$(wget -q -O - "$GLS_URL" --post-data="$post_data")"


if [ "osm" = "$1" ]
then
	echo "$geolocation_json" | sed -e 's#{"location":{"latitude":\(.*\),"longitude":\(.*\),"accuracy":.*},"access_token":".*"}#http://openstreetmap.org/?mlat=\1\&mlon=\2#g'
else
	echo "$geolocation_json"
fi
