#!/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 {
            $record =~ s/$JAVA_HOME/\$JAVA_HOME/g;
            print destFILE $record;
        }
    }
    close(destFILE);
}
close(tlogFILE);
