#!/usr/bin/perl

use POSIX;

@stresstests = `ls stresstest/ | grep -v last | grep -v mstrg | sort`;


open REPORT, ">stresstest.tex";

foreach $st (@stresstests) {

    chop $st;

    `ls stresstest/$st/begin-*.xml*` =~ 
	/begin-(\d\d\d\d)(\d\d)(\d\d)-(\d\d)(\d\d)(\d\d).xml/;
    
    $isostart = sprintf "%d-%d-%d %d:%02d:%02d", $1,$2,$3, $4,$5,$6;

    `ls stresstest/$st/end-*.xml*` =~ 
	/end-(\d\d\d\d)(\d\d)(\d\d)-(\d\d)(\d\d)(\d\d).xml/;
    
    $isoend = sprintf "%d-%d-%d %d:%02d:%02d", $1,$2,$3, $4,$5,$6;

    chop ($start = `date +"%a %d.%m. %H:%M" -d '$isostart'`);
    chop ($end   =  `date +"%a %d.%m. %H:%M" -d '$isoend'`);

    $duration = `date +%s -d '$isoend'` - `date +%s -d '$isostart'`;
    $durstr = sprintf ("%d:%02d",
		       POSIX::floor($duration/3600), 
		       floor($duration%3600/60) );

    chop($ncrashes = `find stresstest/$st -name 'crash-*.xml*' | wc -l`);

    print "$st -- $start -- $end -- $durstr -- $ncrashes\n";

    print REPORT "\\subsection[$start ($durstr h)]";
    print REPORT "{$start - $end ($durstr hours) ";
    #print REPORT "\\textsf{\\textbf{\\large $start - $end ($durstr hours): ";



    if ($ncrashes == 0) {
	print REPORT "OK";
    } elsif ($ncrashes == 1) {
	print REPORT "1 crash";
    } else {
	print REPORT "$ncrashes crashes";
    }

    print REPORT "}\n\n";


    if ( -f "stresstest/$st/comment.tex" ) {
	print REPORT `cat stresstest/$st/comment.tex`;
	print REPORT "\n\n";
    }



    if ($ncrashes > 0) {
	
	@crashes = `find stresstest/$st -name 'crash-*.xml*' | sort`;
	
	foreach $c (@crashes) {
	    
	    chomp $c;

	    $c =~ /crash-(\d\d\d\d)(\d\d)(\d\d)-(\d\d)(\d\d)(\d\d).xml/;
	    
	    $isocrtime = sprintf "%d-%d-%d %d:%02d:%02d", $1,$2,$3, $4,$5,$6;
	    
	    chop ($crtime = `date +"%a %d.%m. %H:%M" -d '$isocrtime'`);

	    print REPORT "\\textbf{$crtime}\n\n";


	    $cmntfile = $c;
	    $cmntfile =~ s/\.xml.*$/.comment.tex/;
	     
	    if ( -f $cmntfile ) {
		print REPORT "Comment: \\parbox[t]{10cm}{";
		print REPORT `cat $cmntfile`;
		print REPORT "}";
	    }
	    
	    print REPORT "\\begin{verbatim}\n";

	    if ( $c =~ /\.xml$/ ) {
		print REPORT `xsltproc /usr/share/pvss_mockup/rstate.xsl $c`;
	    } elsif ( $c =~ /\.xml\.bz2$/ ) {
		print REPORT `bzcat $c | xsltproc /usr/share/pvss_mockup/rstate.xsl -`;
	    } elsif ( $c =~ /\.xml\.gz$/ ) {
		print REPORT `gunzip -c $c | xsltproc /usr/share/pvss_mockup/rstate.xsl -`;
	    } else {
		die "unknown rstate file format ($c)";
	    }
	    print REPORT "\\end{verbatim}\n\n";
	    
	}
	
    }
}


close REPORT;
