#!/usr/bin/perl
use Geo::IP::PurePerl;
use Data::Dumper;
use Net::DNS;
use strict;

my %Info;

while (my $opt=shift @ARGV) {
	if ($opt =~ /^-h/i) { 
		Usage();
	}
	if ($opt =~ /^-/i) { 
		$Info{substr($opt, 1)} = 1;
	}
	#if ($opt =~ /^-f/=i) { 
	#	my $fl = shift @ARGV; 
	#	@FileTypes = split(" ", $fl);
	#}
	if ($opt !~ /^-/i) { unshift @ARGV, $opt; last; }
}

Usage() if $#ARGV < 0;
my $name=shift @ARGV;
if ($name !~ /^[\d.]+$/) {
	#resolve name
	my $res = Net::DNS::Resolver->new;
	my $ans = $res->search($name);
	if ($ans) {
		for my $rr ($ans->answer) {
			next if $rr->type ne "A";
			print "$name = ", $rr->address, "\n";
			WhereIsIt($rr->address);
		}
	} else {
		Usage();
	}
} else {
	WhereIsIt($name);
}

sub WhereIsIt {
	my ($ip) = @_;
	if (!$Info{c}) {
		my $geoip = Geo::IP::PurePerl->new(GEOIP_STANDARD);
		my $co = $geoip->country_code_by_addr($ip);
		print "$co\n";
	} else {
		my $geoip = Geo::IP::PurePerl->open("/usr/share/GeoIP/GeoLiteCity.dat", GEOIP_STANDARD);
		my $rec;
		my @recarr;
		$rec = $geoip->get_city_record_as_hash($ip);
		#@recarr = $geoip->get_city_record($ip);
		for my $k (sort keys %$rec) {
			print "\t $k=$$rec{$k}\n";
		}
		for my $inf (@recarr) {
			print "\t $inf\n";
		}
	}
}

#print Dumper(%$rec);

sub Usage {
		die <<END;
usage: $0 [-h -c <ipaddr|name> ]
	-h this message
	-c city db
END
}

=head1 SYNOPSIS

lookup up location of an ip address or domain name

=head1 SETUP

=item 1 Obviously get this script. 

=item 2 use cpan to install Net::DNS and Geo::IP::PurePerl

=item 3 get country and city db's from maxmind.com (they're free!)

=head1 ChangeLog

=item 0.0.0.0 - first release


