<%args>
$reqkey => undef
$filename=>undef
$user=>undef
$updt=>undef
$vrfy=>undef
$set=>undef
</%args>
<%init>
if ($user){
	
	# procurar no historico para nao duplicar
	my ($reqid, $reqdate, $updated) = $m->comp("/downloads/procs/getreqid.m",reqkey=>$reqkey, user=>$user, extra_info=>1);
	my $done;
	
	# download ja foi efectuado se nao e update e existe historico,
	# ou se e update e no historico consta como actualizado
	$done = 1 if ((!$updt && $reqid) || ($updt && $updated));

	if (!$done){
		
		my $filename = $m->comp("procs/getfilename.m",reqkey=>$reqkey);
		
		if ($filename){
			
			if (-e "/home/apache/htdocs/guianet/downloads/files/$filename.zip"){
				
				my $err = $m->comp("procs/update_history.m", user=>$user, filename=>$filename, updt=>$updt);
				
				if (!$err){
					$m->comp("download.html", user=>$user, filename=>$filename);
				}else{
					$m->comp("error.html"); 
				}
	
			}else{
				
				
				my ($demo, $qrcd, $zone, $zcod, $zdsc, $net1, $agnlist, $agnand) = $m->comp("procs/parsereqkey.m",reqkey=>$reqkey);
					
				if ($qrcd){
		
					my $nolimit = ($user =~ /^nug/) ? 1:0;
					
					my $host = $r->header_in('host');
					my $preview = ($host =~ m/^preview/) ? 1:0;
					my $login = $m->comp("/_shared/procs/get_some_cookie.m",cookie_name=>"login");
					my $lang = $versao; $lang = 1 unless $lang;
					
					my $script = ($vrfy) ? "/home/guiao/cgi/generate_file_vrfy.pl $filename '$set' $nolimit $preview $lang &":
										"/home/guiao/cgi/generate_file2.pl '$login' '$filename' '$qrcd' '$zone' '$zcod' '$zdsc' $net1 '$agnlist' '$agnand' '$nolimit' '$preview' '$lang' &";
					#$m->out($script) if ($user eq 'pcruz');
					my $err = system($script);
									
					if (!$err){
						
						my $err = $m->comp("procs/update_history.m", user=>$user, filename=>$filename, updt=>$updt);
						
						if (!$err){
							$m->comp("download.html", user=>$user, filename=>$filename);
						}else{
							$m->comp("error.html", err=>$err);
						}
						
					}else{
						
						$m->comp("error.html", err=>"erro ao gerar o ficheiro: $err");
						
					}
					
				}else{
					$m->comp("error.html", err=>"criterio invalido");
				}
			}
			
		}else{
			$m->comp("error.html", err=>"nome de ficheiro invalido");
		}
	}else{
		$m->comp("done.html", reqkey=>$reqkey);
	}
}else{
	$m->comp("error.html", err=>"utilizador desconhecido");
}
</%Init>
