#!/usr/bin/perl -T

sub response
{
	(my $status, my $msg)=@_;
	print "Content-Type: text/html\n";
	#print "Status: $status\n";
	print "\n";
	print $msg;
	print "\n";
	exit 0;
}

sub urldecode {
	local($val)=@_;
	$val=~s/\+/ /g;
	$val=~s/%([0-9A-Ha-h]{2})/pack('C',hex($1))/ge;
	return $val;
}


if ($ENV{'REQUEST_METHOD'} ne "GET") { &response(201, "Error: Request method is not GET"); }

my $f=$ENV{'QUERY_STRING'};
$f=~/([-a-zA-Z0-9:;_.\/ ]+)/;
$f=urldecode($f);
(my $person, my $tag)=split(/;/, $f);

if ($f eq "") { &response(200, "No person specified"); }

my $dir="/home/mraento/public_html/pics/$person";
$html="<html><body><h1>Pictures of " . $person;
if ($tag eq "") {
	$html .= "</h1>\n<ul>";
	my @files=<$dir/*.txt>;
	foreach my $f (@files) {
		next if ($f =~ /Test/i);
		$f=~s/\.txt$//;
		$f=~s!.*/([^/]*)!$1!;
		$html .= "<li><a href='pics.pl?" . $person . ";" . $f . "'>";
		$html .= $f . "</li>\n";
	}
	$html .= "</ul>\n";
} else {
	open(IN, "<$dir/${tag}.txt") || &response(201, "cannot open $dir/${tag}.txt");

	$html.=" for " . $tag if ($tag ne "");
	$html.= "</h1>\n";
	$html.="<table>\n";

	while(<IN>) {
		(my $meta, my $filen, my $now, my $desc)=split(/\t/);
		$html .= "<tr><td>";
		if ($filen=~/jpg/) {
			$html .= "<img src='/~mraento/pics/" . $person . "/" . $filen . "' />";
		} else {
			$html .= "<a href='/~mraento/pics/" . $person . "/" . $filen . "' />Media</a>";
		}
		$html .= "</td>\n";
		$html .= "<td>Location: " . $meta . "<br />Time: " . $now;
		$html .= "<br/>" . $desc unless ($desc eq "");
		$html .= "</td></tr>\n";
	}

	$html.="</table>";
}

$html .= "</body></html>";
&response(200, $html);

