#!/usr/bin/perl -w

use strict;
use GD::RPPNG;

my %var;
my %e;

my $pngdir = "/htdocs/web03/gd-rppng/png";
my $tmpdir = "/htdocs/web03/gd-rppng/tmp";

foreach(split(/\&/,$ENV{'QUERY_STRING'})) {
	my ($name,$value)=split(/\=/);
	$name =~ s/\+/ /g;
	$name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$value =~ s/\+/ /g;
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	$value =~ s/\`/\'/g;
	$value =~ s/\'/\\\'/g;
	$var{$name}=$value;
}

print "Content-type: text/html\n\n";

if ( $var{id} =~ /^[0-9]+$/ && $var{code} )
{
	open(CODE,"$tmpdir/$var{id}.txt");
	my $code = <CODE>;
	close(CODE);
	chop $code;

	system("rm $tmpdir/$var{id}.txt");
	system("rm $pngdir/$var{id}.txt");

	print "<html><pre>\n";
	if ( $var{code} eq $code )
	{
		print "AUTHENTICATION OK\n";
	}
	else
	{
		print "AUTHENTICATION ERROR\n";
	}
	print "</pre></html>\n";

}
else
{

	my $image = new GD::RPPNG;

	$image->Config(
		Xsize            => 400,
		Ysize            => 75,
		CharSet          => 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789',
		CodeLen          => 8,
		FontMinPT        => 12,
		FontMaxPT        => 28,
		yDivert          => 10,
		Angle            => 45,
		XLinesFactor     => 10,
		YLinesFactor     => 10,
		Transparent      => 0,
		Colors           => 1,
		bgColor          => 'FFFFFF',
		fgColor          => '000000',
		Code             => '',
		DebugCode        => 0,
	);

	open(FONTS,"ls /usr/X11R6/lib/X11/fonts/truetype/*.ttf |");
	while(<FONTS>)
	{
		chop;
		$image->AddFonts($_);
	}
	close(FONTS);

	my ( $code, $myimage ) = $image->GenImage();

	my $id = int(rand(10000000));

	open(IMAGE,">$pngdir/$id.png");
	print IMAGE $myimage;
	close(IMAGE);
	open(CODE,">$tmpdir/$id.txt");
	print CODE "$code\n";
	close(CODE);

	print "<html><title>GD::RPPNG Demonstration</title>\n";
	print "<h1>GD::RPPNG Demonstration</h1>\n";
	print "<img src=/gd-rppng/png/$id.png><br><br>\n";
	print "<form><input type=hidden name=id value=$id>\n";
	print "Enter code: <input name=code><input type=submit value=AUTH>\n";
	print "</form></html>\n";

	foreach ( `ls $pngdir/*.png; ls $tmpdir/*.txt` )
	{
		chop;
		if ( (stat($_))[9] < time - 900 )
		{
			system("rm $_");
		}
		else { print "\n"; }
	}
}
