
#  ----------------------------------------------------------------------------
#  "THE BEER-WARE LICENSE":
#  <ivan@sanchezortega.es> wrote this file. As long as you retain this notice you
#  can do whatever you want with this stuff. If we meet some day, and you think
#  this stuff is worth it, you can buy me a beer in return.
#  ----------------------------------------------------------------------------
# 
# Geo-IP geolocation extension for TTYtter.
#
# Will fetch your public IP address and, based on that, try to know where you are and set up $lat and $long so your tweets are geolocated.
#
# Precision of IP-based geolocation usually can, at best, locate the city you're at. Don't expect very precise geolocation. Most likely, your tweets will appear at the centre of the city or province or region you're at.
#
# Geolocation happens only the first time you tweet something. It is safe to assume that you won't change cities without quitting ttytter.
#
# Requires: Perl Geo::IP library (might require 'apt-get install libgeoip-dev' and 'cpan Geo::IP') 
# Requires: a Maxmind GeoIP database (hey, why not run a 'apt-get install geoip-database-contrib')
#


use Geo::IP;

print "-- This extension will use the whatismyip.org service to determine your public IP address.\n";


$prepost = sub {

	if(!$Lib_firstrun){
		$Lib_firstrun = true;
		
		our ($lat,$long);
		
		if ($lat || $long )	# Alas, this will not work on Null Island
		{
			print "-- Coordinates already set, GeoIP will not run\n";
		}
		else
		{
			print "-- GeoIP extension will try to locate your public IP address now\n";
			$ip_addr = &backticks($baseagent, '/dev/null', undef, 'http://whatismyip.org', undef, 0, undef);

			my $gi = Geo::IP->open("/usr/share/GeoIP/GeoIPCity.dat", GEOIP_STANDARD);
			my $record = $gi->record_by_addr($ip_addr);
			
			if (!$record ||
			    !$record->latitude  ||
			    !$record->longitude )
			{
				print "-- GeoIP: Sorry, could not geolocate your IP address.\n";
			}
			else
			{
				my $city    = $record->city;
				my $region  = $record->region_name;
				my $country = $record->country_name;
				   $lat     = $record->latitude;
				   $long    = $record->longitude;
				
				print "-- GeoIP: $ip_addr is near $city, $region, $country\n";
			}
		}
	}
	
	
	my $tweet = shift;
	return $tweet;
}


