#! /usr/local/bin/perl

# This script edits the html file which contains pointers to the Kali
#   source code (the .java files), to update the list of files at the
#   end.  It reads the existing file, if there is one, copying
#   everything down to the $tagline, the replaces everything after
#   that line with the new list of files.  (It includes every .java
#   file in the current directory in the new list.)
#
# usage: makesourcehtml FILE [TOPCLASS]
#
#   where FILE is the name of the html file to edit ("source.html").

$SOURCE=$ARGV[0];
$TOPCLASS=$ARGV[1];

$begtag="<!-- Don't modify this section! -->";
$endtag="<!-- End of stuff generated by script -->";
$exptag="<!-- This stuff is generated by the makesourcehtml script -->";

sub print_class_list {
    local($OUT) = @_;
    print $OUT "$begtag
$exptag
<p>
<ul>
";
    if (("$TOPCLASS" ne "") && (-f "$TOPCLASS.class")) {
	print $OUT "  <li><a href=\"$TOPCLASS.html\">$TOPCLASS</a>
	(Start reading with this one.)\n";
    }

    while (<*.class>) {
	s/\.class$//;
	if ("$_" ne "$TOPCLASS") {
	    print $OUT "  <li><a href=\"$_.html\">$_</a>\n";
	}
    }
    print OUT "</ul>\n";
    print $OUT "$endtag\n";
}

sub print_source_list {
    local($OUT) = @_;
    print $OUT "$begtag
$exptag
<p>
<ul>
";
    while (<*.java>) {
	print OUT "  <li><a href=\"$_\">$_</a>\n";
    }
    print $OUT "</ul>\n";
    print $OUT "$endtag\n";
}


sub copy_to_taggroup {
    # Copy lines from IN to OUT, up to but not including the next line
    # matching $begtag, then skip lines in IN up through (and
    # including) the next one matching $endtag.
    local($IN,$OUT) = @_;
    while (<$IN>) {
	if (/$begtag/) {
	    while (<$IN>) {
		if (/$endtag/) {
		    last;
		}
	    }
	    last;
	}
	else {
	    print $OUT $_;
	}
    }
}

if (-f "$SOURCE") {
    rename("$SOURCE", "$SOURCE~");
    open(IN, "<$SOURCE~");
    open(OUT, ">$SOURCE");
    &copy_to_taggroup(IN,OUT);
    &print_class_list(OUT);
    &copy_to_taggroup(IN,OUT);
    &print_source_list(OUT);
    # this just copies the rest of IN to OUT, in case there is more:
    while (<IN>) { print OUT $_; }
    close(IN);
    close(OUT);
} else {
    open(OUT, ">$SOURCE");
    print OUT ("<title>Java Kali Source Code and Documentation</title>

<h1>Java Kali Source Code and Documentation</h1>

<p>
Java Kali consists of the following classes (these are class
documentation files generated with javadoc):
<p>

");
    &print_class_list(OUT);
    print OUT "
<p>
The source code files are:
<p>
";
    &print_source_list(OUT);
}

close(OUT);
