#! /usr/bin/perl -s

# mkindices - policy shell around mkindex tool
# vixie 17jan93 [made less symmetrical but faster]
# vixie 12aug92 [rewrote from sh to perl]
# vixie 31oct92 [happy halloween! cleaning up detrius]

# -s enables: $Verbose

require "fcntl.ph";

$tee = '/usr/bin/tee';
$sort = '/usr/bin/sort';
$compress = '/usr/ucb/compress';
$mkindex = '/usr/local/etc/mkindex';
($EX,$NB) = (2, 4);

chdir('/archive') || die "/archive: $!";
open(lockf, '.') || die "open /archive: $!";
flock(lockf, $EX|$NB) || exit 0;
fcntl(lockf, &F_SETFD, 1) || warn "fcntl: $!";

#
# /rom contains symlinks to ../.N which are filesystems
#

opendir(d, 'rom') || die "/archive/rom: $!";
while ($_ = readdir(d)) {
	next if /^\./;
	next unless -l "rom/$_";
	next unless defined($l = readlink("rom/$_"));
	next unless ($l =~ /^\.\.\/\.(\w)$/);
	die "duplicate rom symlink: $_ -> $l ($1)" if defined($roms{$1});
	$roms{$1} = $_;
	print ".$1 is rom $_\n" if $Verbose;
}
closedir(d);

#
# /pub contains symlinks to ../.N/XXX where XXX must match the dirent name
#

opendir(d, 'pub') || die "/archive/pub: $!";
while ($_ = readdir(d)) {
	next if /^\./;
	next unless -l "pub/$_";
	next unless defined($l = readlink("pub/$_"));
	next unless ($l =~ /^\.\.\/\.(\w)\//);
	next unless $' eq $_;
	die "pub symlink duplicates rom: $_ -> $l" if defined($roms{$1});
	print ".$1 is pub\n" if ($Verbose && !$pubs{$1});
	$pubs{$1} = 1;	# just a flag
}
closedir(d);

open(mkindex, "$mkindex .[0-9] .[a-z]|") || die "$mkindex: $!";

open(byname, "> .Index-byname.$$") || die "byname: $!";
open(byname_z, "| $compress >.Index-byname.$$.Z") || die "byname_z: $!";
open(bytime, "| $sort -n -r >.Index-bytime.$$") || die "bytime: $!";
while (<mkindex>) {
	if (/\s\.(\w)\//) {
		if (defined($roms{$1})) {
			$_ = "$` rom/$roms{$1}/$'";
		} elsif (defined($pubs{$1})) {
			$_ = "$` pub/$'";
		} else {
			print STDERR "?$_";
		}
	}
	print byname;
	print byname_z;
	print bytime;
}

close(mkindex);
close(byname);
close(byname_z);
close(bytime);	# takes a long time since this is when sort(1) runs
system("$compress <.Index-bytime.$$ >.Index-bytime.$$.Z");

foreach $x ('name', 'time') {
	rename(".Index-by$x.$$", "Index-by$x") || die "rename($x): $!";
	rename(".Index-by$x.$$.Z", "Index-by$x.Z") || die "rename($x.Z): $!";
}

unlink <.Index-by{name,time}.*>;

close(lockf);

exit(0);
