#!/usr/bin/perl
use strict;
my %lang=(
	ARA => 'ar',
	CSY => 'cs',
	DAN => 'da',
	DEU => 'de',
	ELL => 'el',
	ENU => 'en',
	ESN => 'es',
	FIN => 'fi',
	FRA => 'fr',
	HEB => 'he',
	HUN => 'hu',
	ITA => 'it',
	JPN => 'ja',
	KOR => 'ko',
	NLD => 'nl',
	PLK => 'pl',
	PTB => 'pt-br',
	ROM => 'ro',
	RUS => 'ru',
	SVE => 'sv',
	TRK => 'tr',
	PRG => 'pt-pt'
	);

sub getlangurl () {
	my $url = shift;
	my $mylang = shift;
	$url=~s/displaylang=en/displaylang=$mylang/g;
	open(g,"wget -O - \"$url\" 2> /dev/null|");
	while(<g>) {
		chomp;
		if (/\<a id=\'btnDownload\' class=\'downloadButton\' href=\'(.*?)\'\>/)  {
			return($1);
		}
	}
	close(g);
}

my $WINLANG = (exists $ARGV[0] ? $ARGV[0] : 'ENU');
my $scriptsdir="scripts/";
open(f,"egrep -hri \"URL\\|($WINLANG|ALL|GENERIC)\" $scriptsdir|");
while(<f>) {
	chomp;
	my @a=split(/\|/);
	$a[2]=~s/\r//;s/^ *//;s/ *$//;
	my $url=$a[2];
	$a[3]=~s/\r//;s/^ *//;s/ *$//;
	my $file=$a[3];
	my $path=$a[3];
	$path=~s#(.*/).*#$1#;
	if ($a[1] =~ /generic/i) {
		$url=&getlangurl($url,$lang{$WINLANG});
		if ($url=~/\.exe$/) {
			my @b=split(/\//,$url);
			$file=$a[3]."/".$b[$#b];
			$path=$a[3];
		} else {
			$url='';
			$file='';
			$path='';
		}
	}
	unless (($url eq '') || (-e $file)) { 
		system("mkdir -p \"$path\";wget --passive-ftp -O \"$file\" \"$url\"");
	}
}
