#!/usr/bin/perl

use CGI;
use DBI;
use Data::Dumper;
use strict;
use diagnostics;

my $cgi = new CGI;

my %params = $cgi->Vars;
my $ip = $ENV{REMOTE_ADDR};
my $referer = $ENV{HTTP_REFERER};

my ($key,$tmp);
my $table="formsvalue";
my $stordir="../exes";
my $formdir="../forms";

sub Fatal($$){
	my $mod = $_[0];
	my $err = $_[1];
	print "Content-Type: text/plain\n";
	print "Connection: close\n\n";
	print "An error occured in $mod: $err\n";
	die "$mod: $err";
}

sub MysqlExec($){
	my $qry = $_[0];
	my $dsn = "DBI:mysql:database=ono_ono;host=localhost";
	my $dbh = DBI->connect($dsn, "ono_ono", "neopaleo")
		|| &Fatal("MysqlExec:connect", "$DBI::errstr");
	$dbh->do($qry)
		|| &Fatal("MysqlExec:do", "$DBI::errstr");
	$dbh->disconnect;
}

sub MissingMandatoryParams(){
	$tmp="missing-params.html";
	open(FILE,"<$formdir/$tmp")
		|| &Fatal("MissingMandatoryParams", "$formdir/$tmp: $!");
	print "Content-Type: text/html\n";
	print "Connection: close\n\n";
	while(<FILE>){
			print;
	}
	close(FILE);
	exit(0);
}

sub CheckMandatoryParams(){
	my @mandat_params = qw/name email zip country/;
	foreach (@mandat_params){
		if(!defined($params{$_}) || !exists($params{$_}) || $params{$_} eq "") {
			&MissingMandatoryParams();
		}
	}
}

sub SanitizeInput(){
	foreach $key (keys %params){
		if ($key !~ /^[a-zA-Z0-9_]+$/){
			&Fatal("SanitizeInput", "Invalid parameters");
		} else {
			if($key =~ /\\/){
				&Fatal("SanitizeInput", "Invalid char '\' in $key value");
			}
		}
		$params{$key} =~ s/\'/\\'/g;
		$params{$key} =~ s/\0/,/g;
		$params{$key} =~ s/,$//;
	}
	if ($params{'l'} !~/^(?:FR|EN|IT|DE)$/i){
		&Fatal("SanitizeInput", "Invalid langage");
	}
	if ($params{'territoire'} !~/^[a-zA-Z0-9_]+$/){
		&Fatal("SanitizeInput", "Invalid guide");
	}
	if(exists $params{'referer'}) {
		if ($params{'referer'} !~/^(?:https?:\/\/[a-zA-Z0-9\/\.:\?=\%_-]+)?$/){
			&Fatal("SanitizeInput", "Invalid referer");
		}
	}
	if(!exists $params{'pc'}) {
		$params{'pc'} = 0;
	}
	if(!exists $params{'mp3'}) {
		$params{'mp3'} = 0;
	}
	if(!exists $params{'gpx'}) {
		$params{'gpx'} = 0;
	}
	if(!exists $params{'v'}) {
		&getLatestVersion();
	}
}

sub getLatestVersion(){
	my($tmp,@files,@ver);

	if ($params{'pc'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-PC-" . uc($params{'l'}) . '-\d+\.\d+\.exe';
	}
	elsif($params{'mp3'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-MP3-" . uc($params{'l'}) . '-\d+\.\d+\.zip';
	}
	elsif($params{'gpx'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-GPX-" . uc($params{'l'}) . '-\d+\.\d+\.zip';
	}
	else
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-" . uc($params{'l'}) . '-\d+\.\d+\.exe';
	}

	opendir(DIR, $stordir) || die "can't opendir $stordir: $!";
	@files = grep { /^$tmp/ && -f "$stordir/$_" } readdir(DIR);
	closedir DIR;
	
	if ($params{'pc'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-PC-" . uc($params{'l'}) . '-(\d+\.\d+)\.exe';
	}
	elsif($params{'mp3'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-MP3-" . uc($params{'l'}) . '-(\d+\.\d+)\.zip';
	}
	elsif($params{'gpx'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-GPX-" . uc($params{'l'}) . '-(\d+\.\d+)\.zip';
	}
	else
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-" . uc($params{'l'}) . '-(\d+\.\d+)\.exe';
	}

	@ver = sort {
		($b =~ /$tmp/)[0] <=> ($a =~ /$tmp/)[0]
	} @files;

	$ver[0] =~ m/$tmp/;

	$params{'v'} = $1;
}

sub ConstructSQL(){
	$tmp = "INSERT INTO $table SET ";
	foreach $key (keys %params){
		$tmp .= "$key='$params{$key}',";
	}
	$tmp .= "date=NOW(),ip='$ip';";

	return($tmp);
}

sub CatExe(){

	if ($params{'pc'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-PC-" . uc($params{'l'}) . "-$params{'v'}.exe";
	}
	elsif($params{'mp3'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-MP3-" . uc($params{'l'}) . "-$params{'v'}.zip";
	}
	elsif($params{'gpx'} == 1)
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-GPX-" . uc($params{'l'}) . "-$params{'v'}.zip";
	}
	else
	{
		$tmp="ONO-" . uc($params{'territoire'}) . "-" . uc($params{'l'}) . "-$params{'v'}.exe";
	}

	open(FILE,"<$stordir/$tmp")
		|| &Fatal("CatExe", "Download temporarily unavailable: $tmp: $!");
	my @stat = stat(FILE);

	print STDERR "Size: $stat[7]";
	print "Content-Type: application/octet-stream\n";
	print "Content-Disposition: filename=$tmp\n";
	print "Content-Length: " . $stat[7] . "\n";
	print "Connection: close\n\n";
	while(<FILE>) { print; }
	close(FILE);
}

sub CatForm(){
#	if($params{'pc'} == 0) {
#		$tmp="ONO-" . uc($params{'territoire'}) . "-" . uc($params{'l'}) . "-$params{'v'}.exe";
#	} else {
#		$tmp="ONO-" . uc($params{'territoire'}) . "-PC-" . uc($params{'l'}) . "-$params{'v'}.exe";
#	}
#	open(FILE,"<$stordir/$tmp") ||
#	{
#		&getLatestVersion();
#		if($params{'pc'} == 0)
#		{
#			$tmp="ONO-" . uc($params{'territoire'}) . "-" . uc($params{'l'}) . "-$params{'v'}.exe";
#		}
#		else
#		{
#			$tmp="ONO-" . uc($params{'territoire'}) . "-PC-" . uc($params{'l'}) . "-$params{'v'}.exe";
#		}
#		open(FILE,"<$stordir/$tmp") || { &Fatal("CatForm", "$stordir/$tmp: $!"); };
#	}
#	my @stat = stat(FILE);
#	close(FILE);
#	my $size= int($stat[7] / 1024 / 1024) + 1 . " MB";
	$tmp="ono-$params{'territoire'}-$params{'l'}.html";
        my $size = '';
	open(FILE,"<$formdir/$tmp")
		|| &Fatal("CatForm","$formdir/$tmp: $!");
	print "Content-Type: text/html\n";
	print "Connection: close\n\n";
	while(<FILE>){
		s/__SIZE__/~ $size/;
		if(/(.*)<!--__REFERER__-->(.*)/){
			print "$1<input type=hidden name=referer value='" . $referer . "'>$2";
		} elsif (/(.*)<!--__CHOICE_PC__-->(.*)/) {
			print "$1<input type=radio name=pc value=0 checked=1>PDA<br><input type=radio name=pc value=1 checked=0>PC$2";
		} elsif (/(.*)<!--__FORCE_MP3__-->(.*)/) {
			print "$1<input type=hidden name=mp3 value=1 />$2";
		} elsif (/(.*)<!--__FORCE_GPX__-->(.*)/) {
			print "$1<input type=hidden name=gpx value=1 />$2";
		} else {
			print;
		}
	}
	close(FILE);
}

sub DumpArgs() {
	print "Content-Type: text/plain\n\n";
	print Dumper(\%params);
	print "\nip = $ip";
	print "\nreferer = $referer\n";
}

&SanitizeInput();
if(defined($params{'enregistrer'})) {
	&CheckMandatoryParams();
	delete $params{'enregistrer'};
	#DEBUG#&DumpArgs;
	#DEBUG#print "Executing: " . &ConstructSQL . "\n";
	&MysqlExec(&ConstructSQL);
	&CatExe();
} else {
	&CatForm();
}

# vim:ts=4:
