#!/usr/bin/perl -w
use strict;
my $add_timestamp=0;
$add_timestamp=shift @ARGV if(@ARGV and "-T" eq $ARGV[0]);
my $recurse=0;
$recurse=shift @ARGV if(@ARGV and "-r" eq $ARGV[0]);
my $sort_by_time=0;
$sort_by_time=shift @ARGV if(@ARGV and "-t" eq $ARGV[0]);
my $usage="usage: $0 [-T] [-r] [-t]\n";
if(@ARGV and "-h" eq $ARGV[0]) {
	print $usage,<<"EOD";
	-T  add timestamp to image URLs
	-r  recurse into subdirectories
	-t  sort images by time
EOD
	exit 0;
}
die $usage if(@ARGV);

my @files=();
if($recurse) {
# Perl's glob() function is fucktastically stupid; it can't handle spaces
	my @dirs=(".");
	while(@dirs) {
		my $dir=shift @dirs;
		opendir(DIR,$dir) or die "opendir: $!";
print "$dir\n";
		$dir=("." eq $dir)?"":"$dir/";
		my @newdir=();
		foreach my $e (sort readdir(DIR)) {
			next if("." eq substr($e,0,1));
			next if("thumbs" eq $e and "" eq $dir);
			if(-d $dir.$e) {
				push @newdir,$dir.$e;
			} elsif($e =~ /.\.(?!css$|html$|js$|xml$)./s) {
				push @files,$dir.$e;
			}
		}
		closedir(DIR) or die "closedir: $!";
		unshift @dirs,@newdir;
	}
} else {
	@files=sort glob "*.*";
	@files=grep {not /\.(?:css|html|js|txt|xml)$/} @files;
}

if($sort_by_time) {
	my %time=map {($_,(stat($_))[9])} @files;
	@files=sort {$time{$a}<=>$time{$b} or $a cmp $b} @files;
}

open(INDEX,">","index.html") or die "open: $!";
if(open(HEADER,"<","HEADER")) {
	print INDEX <HEADER>;
	close(HEADER);
} else {
	print INDEX "<html><head><title>Index of Images</title></head><body>\n";
}
map {
	my $thumb="thumbs/$_";
	$thumb =~ s/\.(avi|mov|mp4|mpg|qt|wmv)$/\.jpg/is;
	if(-f $thumb) {
		print INDEX "<a href=\"$_\"><img src=\"$thumb\"></a>\n";
	} elsif(/([^\/]+)\.(avi|mov|mp4|mpg|pdf|qt|wmv)$/is) {
		print INDEX "<a href=\"$_\">$1</a>\n";
	} else {
		print INDEX "<img src=\"$_";
		if($add_timestamp) {
			my @stat=stat($_) or die;
			print INDEX "?$stat[9]";
		}
		print INDEX "\">\n";
	}
} @files;
if(open(FOOTER,"<","FOOTER")) {
	print INDEX <FOOTER>;
	close(FOOTER);
} else {
	print INDEX "</body></html>";
}
close(INDEX) or die "close: $!";
0;
