#!../perl/perl
#
# Creates index.lst from specified file types.


if ($#ARGV != 1) {
    &printUsage();
    exit;
}

# setup arguments
if ($ARGV[0] =~ /^-[as]$/) {
    $rootDir = "$ARGV[1]";
    $mode = 0;
} else {
    $rootDir = "$ARGV[0]";
    $mode = 1;
}
if ($ARGV[$mode] eq "-a") {
    $suffix = ".apm";
    $baseDir = "$rootDir/bin/proxy/admin/html"
} elsif ($ARGV[$mode] eq "-s") {
    $suffix = ".spm";
    $baseDir = "$rootDir/bin/proxy/httpadmin/html"
}

# get list of index files
if (!-d $rootDir) {
    print "Error: Server root $rootDir does not exist.\n"
}
@files = ();
opendir(SRCDIR, "$baseDir") or
    die "Error: Cannot open $baseDir: $!.\n";
while ($entry = readdir(SRCDIR)) {
    # XXX: svrcore check is a HACK
    if ($entry =~ /$suffix$/ && $entry ne "nescore$suffix" && $entry ne "svrcore$suffix") {
	push(@files, $entry);
    }
}
closedir SRCDIR;

# suck in core index
%master = ();
@categories = ();
assimilateIndex("$baseDir/nescore$suffix");
# suck in everything else
foreach $file (@files) {
    assimilateIndex("$baseDir/$file");
}

# write it out
writeIndex("$baseDir/index.lst");
exit;


sub printUsage {

    print "Usage:  createIndex [-a][-s] <server root>\n";
    print "        -a = create index.lst for admin\n";
    print "        -s = create index.lst for server\n";
}


sub assimilateIndex {
    my $indexFile = shift;
    my $inIndex = 0;
    my $curCategory = "";
    my $oldCategory = 0;

    open(SRC, "$indexFile") or
	print "Error: Cannot open $indexFile: $!.\n";
    while (<SRC>) {
	if (!$inIndex) {
	    if (/^;/) {
		next;
	    } elsif (/^\[INDEX\]/) {
		$inIndex = 1;
		next;
	    }
	}
	if (/^\s*$/) {
	    next;
	}
	if ($inIndex) {
	    if (/^--Category:(.*),(.*)/) {
		if (!$master{$1}) {
		    push(@categories, $1);
		    @{$master{$1}} = ();
		} else {
		    $oldCategory = 1;
		}
		$curCategory = $1;
	    }
	    if ($curCategory) {
		if ($oldCategory) {
		    if (!/^--Category/) {
			push(@{$master{$curCategory}}, $_);
		    }
		} else {
		    push(@{$master{$curCategory}}, $_);
		}
	    }
	}
    }
    close SRC;
}


sub writeIndex {
    my $indexFile = shift;

    open(DEST, "> $indexFile") or
	die "Error: Cannot write $indexFile: $!.\n";
    print DEST "; This list is machine generated.\n";
    print DEST "; Manual edits will be lost.\n";
    print DEST "; \n\n";
    foreach $cat (@categories) {
	if (scalar(@{$master{$cat}}) > 1) {
	    print DEST @{$master{$cat}};
	    print DEST "\n\n";
	}
    }
    close DEST;
}
