#!/usr/bin/perl -w
use strict;
use warnings;

our @tocs;

opendir(my $dfh, ".") or die($!);
while((my $dname = readdir($dfh))) {
	next if($dname =~ /tools/i);
	my $fname = "$dname/__toc__";
	if(-f $fname) {
		open(my $ifh, "<", $fname) or die($!);
		while((my $line = <$ifh>)) {
			chomp $line;
			if($line =~ /[a-zA-Z]/) {
				push @tocs, $line;
			}
		}
		close($ifh);
	}
}
closedir($dfh);

open(my $ofh, ">", "for_upload/toc") or die($!);
# Order, everything else, testlevel, template, updates
my @matchers = ('', 'theme', 'testlevel', 'template', 'update');
print "Gerenating TOC:\n";
for(my $i = 0; $i <= $#matchers; $i++) {
	foreach my $toc (@tocs) {
		my $match = 0;
		if($i == 0) {
			# "everything: Reverse matching, e.g. if anything from
			# element 1 onwards matches, then $match = zero, because we don't want
			# to output that line right now
			$match = 1;
			for(my $j = 1; $j <= $#matchers; $j++) {
				if($toc =~ /$matchers[$j]/i) {
					$match = 0;
				}
			}
		} else {
			if($toc =~ /$matchers[$i]/i) {
				$match = 1;
			}
		}
		next if(!$match);
		print "    $toc\n";
		print $ofh "$toc\n";
	}
}
close($ofh);
		

