#!/usr/bin/perl

my $user = 'dannyman';
my $domain = 'toldme.com';

if( $ARGV[0] ) { $directory = $ARGV[0]; }
else { $directory = './'; }
chdir $directory or die "Couldn't go to directory $directory: $!";

select STDOUT;
$| = 1;
print STDOUT "$0 running on $directory:\n";
open( INDEX, ">index.html" ) or die "Couldn't open index.html: $!";
select INDEX;

opendir(DIR, './') or die "Can't open $directory: $!\n";
foreach $file (readdir(DIR)) {
	if( -d $file && $file !~ /\./ ) { push @dirs, $file; }
	elsif( $file !~ /(^(\.|small-)|\.html$)/ ) { push @pix, $file; }
	elsif( $file !~ /(^.htaccess|\.html$|^\.+$)/ ) {
		if( $file =~ /^(\.|small-)(.*)/ && (! -e $2) ) {
			print STDOUT "Removing $file.\n";
#			unlink $file;
		}
	}
}

print<<__HEAD;
<html><head>
<title>$user\'s Pictures: $directory</title>
<link rev="made" href="mailto:$user\@$domain">
<link rel="stylesheet" href="/~$user/css/default.css" type="text/css">
</head><body>

<h1>$directory</h1>
<hr>
__HEAD

if( @dirs ) { print "<p align=\"center\">"; }
foreach $dir (sort @dirs) { print "[<a href=\"$dir\">$dir</a>]\n"; }
if( @dirs ) { print "</p>"; }

if( @pix ) {
	foreach $pic (sort @pix) {
		if(! -s "small-$pic" ) {
			print STDOUT "Generating small-$pic ... ";
			$spic = $pic; $spic =~ s/(\W)/\\$1/g;
			system "cp $spic small-$spic";
			system "mogrify -geometry 150x150 small-$spic";
			print STDOUT "DONE!\n";
		}
		$size = (stat($pic))[7];
		if(! -s ".$pic" ) {
			print "<p><a href=\"$pic\"><img src=\"small-$pic\">$pic</a>";
			print " ($size bytes)\n";
		}
		else {
			$comment = '<p>';
			print<<__THEAD;
<table>
<tr><th><a href="$pic">$pic</a><td>($size bytes)
<tr><td align="center"><a href=\"$pic\"><img src=\"small-$pic\"></a>
<td>
__THEAD
			open( COMMENT, ".$pic" ) or die "Couldn't open $pic: $!";
			while( <COMMENT> ) { $comment .= $_; }
			$comment =~ s/\n\n/<p>/gs;
			print "$comment\n</table>\n";
		}
	}
	if( @dirs ) { print "<p align=\"center\">"; }
	foreach $dir (sort @dirs) { print "[<a href=\"$dir\">$dir</a>]\n"; }
	if( @dirs ) { print "</p>"; }
}

foreach $dir (sort @dirs) { system "$0 $dir"; }

$date = gmtime((stat('./'))[9]);
print<<__TAIL;
<hr>
<p align="center"><a href="../">Parent Directory</a>
<br><a href="/~$user/Pictures/">Pictures</a>
<br><a href="/~$user/">H O M E</a>
</p>
<hr width="100%">
<address>This directory last changed $date
&lt;<a href="mailto:$user\@$domain">$user\@$domain</a>&gt;
</address>
</body></html>
__TAIL
