#!/usr/bin/perl

#
# Generate rerun.sh by .tlog file.
# Actually the script only does substitute JAVA_HOME value to $JAVA_HOME
#

if ($#ARGV != 1) {
    print "Usage: $0 tlog_filelist java_home\n";
    exit (1);
}

$tlogFilelist = $ARGV[0];
$JAVA_HOME = $ARGV[1];

open (masterFILE , "$tlogFilelist") || die "Can't open $tlogFilelist: $!\n";

while ($tlogFilename = <masterFILE>)
{
    unless (open(tlogFILE, "$tlogFilename")) {
        print STDERR "Can't open $tlogFilename: $!\n";
        next;
    }

    $tlogDirname = $tlogFilename;
    $tlogDirname =~ s/\/[^\/]+$//;

    open(destFILE, ">$tlogDirname/rerun.sh");

    print destFILE <<kitakita;
#!/usr/bin/sh
#===============================================================================
# Generated rerun script
#===============================================================================
JAVA_HOME=$ARGV[1]
export JAVA_HOME

pwdir=`pwd`
kitakita
#==========================End of Header creation =====================

    while( $record = <tlogFILE> )
    {
        # skip comments and empty lines
        if ($record =~ "^#" || $record =~ /^\s*$/) {
            print destFILE $record;
        }
        # skip JAVA_HOME settings
        elsif ($record =~ /^\$JAVA_HOME=/) {
            print destFILE $record;
        }
        else {
            # substitute JAVA_HOME value by JAVA_HOME variable
            $record =~ s/$JAVA_HOME/\$JAVA_HOME/g;

            # fix problems with unquoted -debugee.vmkeys, bug id 6989082
            if ( ($record =~ /^\s*TONGA_EXECUTE=/) && ($record =~ /-debugee\.vmkeys=/) ) {
               $TONGA_EXECUTE = $record;
               $TONGA_EXECUTE =~ s/^\s*TONGA_EXECUTE=\s*"//;
               $TONGA_EXECUTE =~ s/"\s*//;
               
               $TONGA_EXECUTE =~ s/-debugee\.vmkeys=\${([a-zA-Z_]+)}/-debugee\.vmkeys="\${$1}"/;
            } elsif ( $record =~ s/^\s*\${TONGA_EXECUTE}\s+//) {
               if (length($TONGA_EXECUTE) > 0) {
print yea;
                 $record = "$TONGA_EXECUTE $record";
               } else {
                 $record = "\${TONGA_EXECUTE} $record";
               }
            }

            print destFILE $record;
        }
    }
    close(destFILE);
}
close(tlogFILE);
