#! /usr/bin/perl
use CGI;
use HTML::Entities;
use POSIX;
use strict;
use warnings;
require './config.pm';

# Find the latest N PNG thumbnails. Somewhat ineffective, but I assume 
# we'll get to that later :-)
my @thumbnails = (sort { -M $a <=> -M $b } <$pdfweb::config::outputdir/*.png>);
my $real_show_last = scalar @thumbnails;
if ($real_show_last > $pdfweb::config::show_last) {
	$real_show_last = $pdfweb::config::show_last;
}

# This is probably the simplest place to clean up files that we no longer
# need having around.
for my $t (@thumbnails[$pdfweb::config::show_last..$#thumbnails]) {
	if (-M $t > $pdfweb::config::minimum_age) {
		(my $base = $t) =~ s/\.png$//;
		my @to_delete = <$base*>;

		warn "Deleting " . join(', ', @to_delete);
		unlink @to_delete;
	}
}

# Sorry, no HTML templating. I didn't want to pull in yet another
# dependency :-)

print <<"EOF";
Content-type: text/html; charset=utf-8

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE
  html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>PDF converter : sesse.net</title>
    <link rel="stylesheet" href="http://www.sesse.net/sesse.css" type="text/css" />
    <link rel="stylesheet" href="pdfweb.css" type="text/css" />
    <link rev="made" href="mailto:sgunderson\@bigfoot.com" />
    <meta name="MSSmartTagsPreventParsing" content="TRUE" />
  </head>
  <body>
    <h1>Last $real_show_last uploads</h1>
    
    <p><a href="http://pdf.sesse.net/">Back to the converter</a></p>
EOF

for my $t (@thumbnails[0..$pdfweb::config::show_last-1]) {
	(my $descname = $t) =~ s/\.png$/.desc/;
	open DESC, "<$descname"
		or next;
	chomp (my $desc = <DESC>);
	close DESC;

	if (length($desc) > 30) {
		# Is this <abbr> abuse?
		$desc = HTML::Entities::encode_entities(substr($desc, 0, 30)) . " <abbr title=\"" .
			HTML::Entities::encode_entities($desc)
		. "\">...</abbr>";
	} else {
		$desc = HTML::Entities::encode_entities($desc);
	}

	my $time = (stat($t))[9];
	my $date = POSIX::strftime("%Y-%m-%d %H:%M", localtime($time));
	$t =~ s#^.*/##;
	(my $pdfname = $t) =~ s/\.png$//;

	print <<"EOF";
<div class="pdfthumbnail">
  <p class="thumb"><a href="output/$pdfname"><img src="output/$t" alt="PDF thumbnail" /></a></p>
  <p class="desc">$desc</p>
  <p class="date">$date</p>
</div>
EOF
}

print <<"EOF";

    <p class="copyright">Web PDF converter, &copy; 2005 <a href="http://www.sesse.net/">Steinar H. Gunderson</a>.</p>
  </body>
</html>	
EOF
