#!/usr/local/bin/perl

use IO::File;
#use strict;

my $dir = ".";
my $imageMagickPath = "/usr/bin";
my $fieldSeparator = "\@-\@-\@-\@";

#
# Read files with specially-formed names from this directory.
#
opendir(DIR, $dir);
my (@raw_files) = sort(grep(/^web-200\d{5}\..*/, readdir(DIR)));
closedir(DIR);

#
# If there are multiple files for a single day, only pick one.
# HTML files trump all others.
#
my @files;
my $cur_base = "";
my $best_ext = "";
foreach my $file (@raw_files) {
	my ($base, $ext) = $file =~ /(.*)\.(.*)/;
	if ($base eq $cur_base) {
		if ($ext eq "html") {
			$best_ext = $ext;
		}
		else {
			# could make JPG trump PNG or whatever.  For now, last to appear wins.
			if ($best_ext ne "html") {
				$best_ext = $ext;
			}
		}
	}
	else {
		if ($cur_base ne "") {
			push @files, "$cur_base.$best_ext";
		}
		$cur_base = $base;
		$best_ext = $ext;
	}
}
if ($cur_base ne "") {
	push @files, "$cur_base.$best_ext";
}

#
# Build the TOC.
#
foreach my $file (@files) {
	my ($base, $ext) = $file =~ /(.*)\.(.*)/;

	my ($date) = $base =~ /web-(\d*)/;
	my $type = "";
	my $details = "";

	if ($ext eq "html") {
		$type = "HTML";
	}
	else {
		#
		# Hopefully, it's an image.
		#
		$type = "IMG";
		my $geom = "";
		if ($imageMagickPath ne "") {
			open(IDOUT, "$imageMagickPath/identify -ping $file 2>&1 |");
			if (IDOUT) {
				while (<IDOUT>) {
					if (/\s([0-9]+x[0-9]+)/) {
						$details = "GEOM:$1";
						last;
					}
				}
				close(IDOUT);
			}
		}
	}

	my $entry = "";
	$entry .= "DATE:" . $date . $fieldSeparator;
	$entry .= "TYPE:" . $type . $fieldSeparator;
	$entry .= "FILE:" . $file;
	if ($details ne "") {
		$entry .= $fieldSeparator . $details;
	}

	print "$entry\n";
}

