#!/usr/bin/perl

use strict;

my $BR        = 'KRB67ikH3'; # http://surfin.infotel.bg:2000/tel/wuk.js (Look at the bottom ;)
my $url       = 'http://surfin.infotel.bg:2000/wp/wph1.PRINT_REZ';

my $stdparams = '&ST=1&BR='.$BR.'&ekod_ul=';
my $stdparams2= '&CPATNAME=&CADDRESS=';

my $referer   = "-e 'http://surfin.infotel.bg:2000/wp/wp.cnt_usr'";
my $referer   = "";
my $ua        = "-A 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.0) Gecko/20020529'";
my $ua        = "-A ' '";
my $proxy     = "-x 212.124.64.5:3128";
my $proxy     = "";

my @letters = ('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Ü','Þ','ß');

my %cities = (
	BLAGOEVGRAD=>'4279:100',
	BOURGAS=>'7079:200',
	CHEPELARE=>'80371:2000',
	DOBRICH=>'5:2300',
	GABROVO=>'2:66',
	KIUSTENDIL=>'41112:900',
	LOVECH=>'43952:1000',
	MONTANA=>'48489:1100',
	PAZARDZHIK=>'55155:1200',
	PERNIK=>'55871:1300',
	PLEVEN=>'56722:1400',
	PLOVDIV=>'56784:1500',
	RAZGRAD=>'10:1600',
	RUSE=>'7000:1700',
	SHUMEN=>'150:2600',
	SILISTRA=>'1:1800',
	SLIVEN=>'89:1900',
	SMOLIAN=>'67653:2000',
	SOFIA=>'68134:2800',
	TARGOVISHTE=>'170:2400',
	VARNA=>'23:300',
	VELIKO_TARNOVO=>'10447:400',
	VIDIN=>'10971:500',
	VRATSA=>'12259:600'
);

if ($#ARGV < 2) {
	print "Usage: $0 mode city surnames_file [1,2,3,4]\n\n";
	print "  Modes: first, firstspecial, second\n  Cities:\n";
	foreach my $city (sort keys %cities) {
		print "   $city\n";
	}
	print "\n";
	exit;
}

my $MODE     = $ARGV[0];
my $CITY     = $ARGV[1];
my $SURNAMES = $ARGV[2];
my $SPECIAL  = $ARGV[3];

if ($cities{$CITY}) {
	print "Loading surnames...\n";
	my @surnames = `cat $SURNAMES`;
	chomp(@surnames);

	my ($settl,$creg) = split(":",$cities{$CITY});
	mkdir($CITY);

	# First mode
	if ($MODE eq 'first') {
		print "Generating URLS...\n";
		my $curline = 0;
		open(URLFILE,">$CITY.$MODE.sh");
		foreach my $surname (@surnames) {
			$curline++;
			my $line = sprintf("%05d",$curline);
			my $postdata = "CREG=".$creg.$stdparams."&SETTL=".$settl."&SLASTNAME=".$surname."&SFIRSTNAME=".$stdparams2;
			print URLFILE "[ -f $CITY/$line.htm ] || curl $proxy -d \"$postdata\" $ua $referer -o $CITY/$line.htm -f $url\n";
		}
		close(URLFILE);
	}

	# First special mode
	if ($MODE eq 'firstspecial') {
		print "Generating URLS...\n";
		my $curline = 0;
		my ($settl,$creg) = split(":",$cities{$CITY});
		mkdir($CITY);
		open(URLFILE,">$CITY.$MODE.sh");
		my @surnames_spec;
		foreach my $special (split(",",$SPECIAL)) {
			$curline=0;
			my $surname = $surnames[$special - 1];
			foreach my $letter (@letters) {
				$curline++;
				my $line = sprintf("%03d",$curline);
				my $postdata = "CREG=".$creg.$stdparams."&SETTL=".$settl."&SLASTNAME=".$surname."&SFIRSTNAME=$letter".$stdparams2;
				print URLFILE "[ -f $CITY/$special-$line.htm ] || curl $proxy -d \"$postdata\" $ua $referer -o $CITY/$special-$line.htm -f $url\n";
			}
		}
		close(URLFILE);
	}

} else {
	print "Unknown city!\n";
}
