#!/usr/bin/perl
#!/space/imail/perl/bin/perl

=head1 NAME
  IndexDir - Make an HTML index of the current directory.

=head1 SYNOPSIS
  IndexDir [dir]..

=head1 DESCRIPTION
  This is useful when your web server is configured with -Indexes, so it
  doesn't automatically generate directory listings.  Just put these in
  your makefile, and a make command will build the index.html from the
  directories listed.  The default directory is '.', as you might expect.

  index.html: *; IndexDir >index.html

=head1 OPTIONS

  -s/pat/rpl/
    This means to do a (perl) pattern match and replacement on the names.
    The replacement is what will be shown.  This can be used to abbreviate
    file names, strip off suffixes, etc.  As a special case:

  -s/pat//
    This means to ignore files whose names match the pattern.  We always 
    ignore all files whose names start with a dot ("."); this is normal
	for Unix software, of course..

=head1 FILES

=head1 BUGS

=head1 SEE ALSO

=head1 AUTHOR
  John Chambers <jc@trillian.mit.edu>
=cut

$| = 1;
($me = $0) =~ s".*/"";

@hdr = ();		# Header lines, if any.

for $name (@ARGV) {
	if ($name =~ /^-s(.)(.*)$1(.*)$1$/) {
		$pat = $1;
		$rpl = $2;
	} else {
		if (-f $name) {
			push @file, $name;
		} elsif (-d $name) {
			if (-f "$name/HEADER.html") {
				if (open(HDR,"$name/HEADER.html")) {
					for $h (<HDR>) {push @hdr, $h}
					close HDR;
				} else {
					print STDERR "$me: Can't read \"$name/HEADER.html\" ($!)\n";
				}
			}
			if (opendir(DIR,$name)) {
				@names = grep !/^\./, readdir(DIR);
				close DIR;
				for $f (@names) {
					($path = "$name/$f") =~ s"^\./"";
					push @file, @path;
				}
			} else {
				print STDERR "$me: Can't read \"$name\" ($!)\n";
			}
		} else {
			chomp($cwd = `pwd`);
			print STDERR "$me: Can't find \"$name\" in \"$cwd\"\n";
		}
	}
}
if (!@file) {
			if (-f "HEADER.html") {
				if (open(HDR,"HEADER.html")) {
					for $h (<HDR>) {push @hdr, $h}
					close HDR;
				} else {
					print STDERR "$me: Can't read \"HEADER.html\" ($!)\n";
				}
			}
	if (opendir(DIR,".")) {
		@names = grep !/^\./, readdir(DIR);
		close DIR;
		for $f ('..', @names) {
			($path = "$f") =~ s"^\./"";
			push @file, $path;
		}
	} else {
		print STDERR "$me: Can't read \".\" ($!)\n";
	}
}
if (@hdr) {
	print @hdr;
	print "<hr>\n";
}
$flen = 20;
$slen =  4;
for $p (@file) {
	if (-d $p) {$p .= '/'}
	if (($l = length($p)) > $flen) {$flen = $l}
	@finfo = stat($p);
	$fsize{$p} = $finfo[7];
	$mtime{$p} = $finfo[9];
	if (($l = length($finfo[7])) > $slen) {$slen = $l}
}

print "<pre>\n";
print "<tt>\n";

for $p (sort @file) {
	&oneurl($p);
}
print "</tt>\n";
print "</pre>\n";


sub oneurl {
	local($p) = @_;
	print(' ' x ($slen - length($fsize{$p})));
	print $fsize{$p};
#	print("." x ($flen - length($p)));
	print ' ';
	($ss,$mm,$hh,$DD,$MM,$YY) =  gmtime($mtime{$p});
	printf("%d/%02d/%02d %2d:%02d:%02d UT",1900+$YY,1+$MM,$DD,$hh,$mm,$ss);
	print ' ';
	print "<a href=\"$p\">$p</a> ";
	print "\n";
}
