#!/usr/local/bin/perl
eval ' exec /usr/local/bin/perl -S $0 "$@" '
	if $running_under_some_shell;
	shift if(join("", @ARGV) eq ""); # Xenix Kludge

# $Header: /u/usr/cvs/lbin/getopt.perl,v 1.14 2000/10/19 23:04:35 bill Exp $
# $Date: 2000/10/19 23:04:35 $
# @(#) $Id: getopt.perl,v 1.14 2000/10/19 23:04:35 bill Exp $

use File::Basename;
my ($progname, $dirname) = fileparse($0); # save this very early
chop($dirname);

do "/usr/bin/csspath.perl" unless $ENV{'USR_BIN_CSSPATH'};

$USAGE = "
#
#   Usage: $progname [-v] [-e var=value]
#
# Options   Argument    Description
#   -f      filename    File containing images to index
#   -c      integer     Number of columns (default 5)
#   -v                  Verbose
#
";

sub usage {
	die join("\n",@_) .
	"\n$USAGE\n";
}
# This is in the prototype because it's frequently fiddled on a
# case by case basis for local debugging.
sub run {
	my $cmd = shift;
	print STDERR "system($cmd)" if $verbose;
	system($cmd);
}
# do "getopts.pl";

use strict;

use Getopt::Long;
Getopt::Long::Configure qw {require_order bundling};

# declare global variables
use vars (
	'%opt_e',			# environment settings
	'$opt_h',			# print help
	'$opt_v',			# Verbose
	'$verbose',
	'$opt_c',
	'$opt_f',
);
usage("Invalid Option") unless GetOptions (
	'-e=s%',			# environment variables
	'-h|help',
	'-v|verbose',
	'-c|columns=n',
	'-f|file-list=s',
);
for (keys %opt_e) {
	$ENV{$_} = $opt_e{$_};
}
$verbose = '-v' if $opt_v;
my $suffix = $$ unless $opt_v;

sub un_taint {
	my $PATH = $ENV{'PATH'};
	$ENV{'PATH'} = $PATH;
	$> = $<;	# make it ignore taintedness (
	$) = $(;	# gids )
}
# &un_taint();	# make it ignore taintedness

# this sets TMPDIR to the largest available temporary directory.
require 'bigtmp.pl'; my $TMPDIR = &bigtmp();

$\ = "\n";	# use newlines as separators.

my $seq = 0;
my $fmt = qq(convert '%s' -geometry 80x60 %s);

$opt_c = 5 unless $opt_c;
open(INDEX, "> index.html");

print INDEX "<title>Index to @ARGV</title>";
print INDEX "<h1>Index to @ARGV</h1>";
print INDEX "<table col=$opt_c>";

open(INPUT, ($opt_f ? $opt_f : "gfind @ARGV -follow -type f | sort |"));
my @table_lines = ();

while(<INPUT>) {
	chomp;
	next unless(/\.(jpg|gif|tif)$/i);
	$seq++;
	my $thumbnail = sprintf("image_%04d.jpg", $seq);
	my $cmd = sprintf($fmt, $_, $thumbnail);
	run($cmd) unless -f $thumbnail;
	push(@table_lines,
		qq(<td><A href="file:$_"><img src="$thumbnail"></a></td>));
}
while(@table_lines) {
	print INDEX join("\n\t", '<tr>',
		splice(@table_lines, 0, $opt_c),
		'</tr>');
}
print INDEX "</table>";

__END__
convert 01100076.jpg -geometry 160x120 /tmp/test.jpg
