#!/usr/bin/perl -w
use strict;
use DBI;
use CGI;
use HTML::Template;
use Config::General;
use lib "geo/Geo-IP-1.38/lib/";
use Geo::IP; 

#open the config file
my $conf              = new Config::General(
                                             -ConfigFile     => ".htmosaic_conf",
                                             -ExtendedAccess => 1,
                                            );
#read database data
my $sql_db      = $conf->obj('database')->sql_db;
my $sql_host    = $conf->obj('database')->sql_host;
my $sql_user    = $conf->obj('database')->sql_user;
my $sql_pass    = $conf->obj('database')->sql_pass;

#general mosaic data
my $url    = $conf->obj('general')->url;


# Fetch passed values like the version
my $buffer = $ENV{'QUERY_STRING'}; 
my %form;
my @pairs = split(/&/, $buffer);

foreach my $pair (@pairs)
{
    my @splitIt = split(/=/, $pair);
    $splitIt[1] =~ tr/+/ /;
    $splitIt[1] =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $splitIt[0] =~ tr/+/ /;
    $splitIt[0] =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    $form{$splitIt[0]} = $splitIt[1];
}

#get type
my $mosaicType = "desktop";
if ($form{"type"}) {
    $mosaicType = $form{"type"};
}

# Connect to the database.
my $dbh = DBI->connect("DBI:mysql:database=$sql_db;host=$sql_host",
                       "$sql_user", "$sql_pass",
                       {'RaiseError' => 1});
               
my $ip = $ENV{"REMOTE_ADDR"};


# get location 
my $gi;
eval{$gi =   Geo::IP->open( "geo/GeoLiteCity.dat", GEOIP_STANDARD );}; 
if ($@){print "Error: $@\n";}
my $r;
eval{$r = $gi->record_by_name($ip);};
if ($@){print "Error: $@\n";}


#insert into DB
if ($r) {
    my $sql_string = "INSERT INTO statisticLocation(id,ip,country_code,country_name,city,region_name,latitude,longitude) VALUES";
       $sql_string = $sql_string." (UNIX_TIMESTAMP(),'".$ip."','".$r->country_code."','".$r->country_name."','".$r->city."','".$r->region_name."',".$r->latitude.",".$r->longitude.")";
       $sql_string = $sql_string." ON DUPLICATE KEY UPDATE ID = UNIX_TIMESTAMP()";
    $dbh->do($sql_string);  
}
                       
$dbh->disconnect();    

#forward to MOSAIC
my $cgi = new CGI;
    
# if desktop version -> forward to jnlp
if ($mosaicType eq "desktop") {
    print $cgi->redirect($url."jar/Mmodeling.jnlp"); 
}

exit;
