#!/usr/bin/perl -w
#Скрипт для застройки указанной планеты максимальным количеством
#добывалок указанного типа;
use strict;
use POSIX;
use LWP::UserAgent;
use HTTP::Cookies;
use Compress::Zlib;
$| = 1;

my $login = shift;
my $pass = shift;

our $url_base='.the-game.ru';
our $cookies=HTTP::Cookies->new('file'=>'./cookies.lwp','autosave'=>0);
my $browser=LWP::UserAgent->new('agent' => 'Opera/9.10 (X11; Linux i686; U; en)',
								  'cookie_jar' => $cookies,
								  'requests_redirectable' => ['GET', 'POST']);
$browser->default_header('Accept' => 'text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1',
						'Accept-Charset' => 'iso-8859-1, utf-8, utf-16, *;q=0.1',
						'Accept-Language' => 'ru,en;q=0.9',
						'Accept-Encoding' => 'deflate, gzip, x-gzip, identity, *;q=0',
						);
############# MAIN PROGRAMM #############

my $AccType = &Login;

	print "Уажите (через двоеточие) координаты планеты-цели (X:Y): ";
		my $mine_planet = ;
		chomp ($mine_planet);
	print "Укажите вид добывающей постройки (1 - шахта, 2 - биоферма, 3 - генератор): ";
		my $build_ID = ;
		chomp ($build_ID);
	&StorePlanetMines($AccType, $mine_planet, $build_ID);


############# PROCEDURES #############
sub StorePlanetMines($$$){
 my $AccType = $_[0];
 my $mine_planet = $_[1];
 my $build_ID = $_[2];
 my $source;
 my $mine_count;
 
 my $response=$browser->get("http://$AccType".$url_base.'/frames/planetinfo/on/planet/?planetid='.$mine_planet);
 $source=Compress::Zlib::memGunzip(\($response->content)[0]);
 if ($source =~ /title="Поверхность: (\d{1,2})"/){
 	$mine_count = int ((($1 * 2000)- 6000)/5000);
 	print "Planet: $mine_planet Area: $1 Mines: $mine_count \n";
 }
 else {warn "Error: $!";}
 if ($source =~ m#>Свободно(\d{1,3}) (\d{1,3})#){
 	print "OK. $1 $2 peoples is free. Building begine.\nProcess " if $1 >= 5;
 	print "Не хватает свободного населения (необходимо минимум 5000). Попробуйте позже.\n" if $1 < 5;
 	for (1..$mine_count){
 		$response = $browser->get ("http://$AccType".$url_base.'/frames/planet_buildings/on/planet/?planetid='.$mine_planet.'&action=add_building_to_que&building_id='.$build_ID);
		do{print STDOUT "Connection error: ".$response->status_line,"\r\n";next;} unless $response->is_success;
	print '.';
	sleep (rand (2)+1);
 	}
 }   
# http://free.the-game.ru/frames/planet_buildings/on/planet/?planetid=1405:1554&action=add_building_to_que&building_id=1
 
}

sub Login(){
# login
 my $source;
 my $response=$browser->post('http://www.the-game.ru',
    [
     'action'=>'login',
     'login'=>$login,
     'pwd'=>$pass,
    ]);
	$source=Compress::Zlib::memGunzip(\($response->content)[0]);
	$pass=~s/#/%23/;
	$response=$browser->get('http://www'.$url_base."/overview/?&action=login&login=$login&pwd=$pass") if $source=~/content)[0]);
	do{print STDOUT "\r\n!WARNING! $login: invalid user name and/or password. Please check this manually.\r\n";next;}
		if $source=~/status_line,"\r\n";next;} unless $response->is_success;
		my $CurrentUser=$1 if $source=~/.+?::.+?::\s(.*)<\/title>/;
		my $myID=$1 if $source=~/var PlayerId=(\d{1,7});/;
		my $turn=$1 if $source=~/var TurnN=(\d{4});/;
		#our $AccType='free' if $source=~/Paid=0;/; # действительно для старой вселенной, для новой:
        our $AccType='www' if $source=~/Paid=0;/;
		$AccType='www' if $source=~/Paid=1;/;
		print STDOUT "\r\n>>>User logged in us player $CurrentUser (ID=$myID)\n";
  return ($AccType);
}

sub Logoff($){
#logoff
 my $AccType = $_[0];
 print STDOUT "\r\nDo Logoff\r\n";
 $browser->get("http://$AccType".$url_base.'/logoff/');
}