#!/usr/local/bin/perl
# replaceRuntimeValues.pl
# 
# Copyright (c) 2006, Oracle. All rights reserved.  

if($#ARGV < 2)
{
	print "Usage: $0 <runtime xml template file> <new-runtime-xml filename> <properties file> \n";
	exit 1;
}
$XMLFILE=$ARGV[0];
$XMLNEWFILE=$ARGV[1];
$PROPFILE=$ARGV[2];

chomp($XMLFILE);
chomp($XMLNEWFILE);

#open(NEWFILE,">$XMLFILE");
#close(NEWFILE);
#chmod 0600, $XMLFILE;

open(NEWFILE,">$XMLNEWFILE");
close(NEWFILE);
chmod 0600, $XMLNEWFILE;

$XMLFILENAME=$XMLFILE;
$XMLFILENAME=~s/.*\/(.*)/$1/;
chomp($PROPFILE);
if(!( -f $XMLFILE && -r $XMLFILE))
{
	print "Runtime xml file is not readable: $XMLFILE\n";
	exit 2;
}
if (! -r $PROPFILE)
{
	print "Properties file is a not readable: $PROPFILE\n";
	exit 3;
}

my %PROP;

# Read the properties file
readPropFile($PROPFILE);

# Replace the properties in the RuntimDataXML with the values
open(XFILE,"<$XMLFILE");
open(XNEWFILE,">".$XMLNEWFILE);
@XFILE_DATA=<XFILE>;
close (XFILE);
foreach $line (@XFILE_DATA)
{
	while(($property,$value)= each( %PROP))
	{
		#print $property."\n";
		#replace ^usecase_variable^
		if($line=~/\^$property\^/)
		{
			$line=~s/\^$property\^/$value/g;
			#print $line.":\n";
		}
		#replace old_value==new-value
		elsif($line=~/(value|Name)=\"$property/i)
		{
			$line=~s/(value)=(\".*?\") /$1=\"$value\" /ig;
			#print $line.":\n";
		}
	}
	print XNEWFILE  $line;
}
close(XNEWFILE);



# Method to read the properties file
sub readPropFile
{
 my ($prop_file)=@_;
 #print $prop_file;
 open(PFILE,"<$prop_file");
 while(<PFILE>)
 {
        chomp();
        if (!(/^ *#/)) # Ignore comments
        {
                @T_PROP=split(/=/);
                $T_PROP[0]=~s/ //;
                chomp($T_PROP[0]);
                chomp($T_PROP[1]);
                $T_PROP[1]=~s/ $//;
                if($T_PROP[0])
                {
                    $PROP{$T_PROP[0]}=$T_PROP[1];
                }
        }
 }
 close (PFILE);
}
