#!/usr/local/bin/perl
# 
# $Header: updateCSProps.pl 16-sep-2005.07:05:27 audupi Exp $
#
# updateCSProps.pl
# 
# Copyright (c) 2005, Oracle. All rights reserved.  
#
#    NAME
#      updateCSProps.pl - Updates cs.properties.
#
#    DESCRIPTION
#      Updates OH/clone/config/cs.properties with required parameters.
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    audupi      09/16/05 - audupi_bug-4579173
#    audupi      09/06/05 - Creation
# 
use English qw(-no_match_vars);  
use File::Spec;

# Parses parameters passed as arguments to this script. 
# Currently, only the "-oraclehome" flag is handled by this script.
# The other flags are assumed to be required to be passed to setup.exe
# @return - parameters provided, with OH being the first element, and the
# remaining parameters following it.
sub parseParams()
{
	my @args = ();
	my $numArgs = scalar(@ARGV);
	if ($numArgs < 3)
	{
		printUsage();
		exit (255);
	}
	my $arg = shift(@ARGV);
	if ($arg eq "-oraclehome")
	{ # the first element of our param-array will be the Oracle-home.
		unshift (@args, shift(@ARGV));
	}
	else
	{
		printUsage();
		exit (255);
	}
	my $cnt = 1;
	# now add all the remaining args into the array.
	foreach $arg (@ARGV)
	{
		@args[$cnt] = $arg;
		$cnt++;
	}
	return @args;
}

# prints usage for this script.
sub printUsage()
{
	print "Usage: $0 -oraclehome <ORACLE_HOME> <flags to be passed to setup.exe>\n";
}

# updates cs.properties in the given OH with the parameters provided.
# @params OH Location, Parameters to be added to cs.properties.
sub updateCSProperties
{
	my ($oracleHomeLoc, @params) = @_;
	my $csProperties = File::Spec -> catfile ($oracleHomeLoc, "clone", "config", "cs.properties");
	if (-e $csProperties)
	{ #add given parameters to clone-command-line in cs.properties
		open(CS_PROPS, $csProperties) || die " Cannot open file $csProperties for read. Reason: $!\n";
		my @keyValues = <CS_PROPS>;
		close(CS_PROPS);
		my $updated = "false";
		foreach $keyVal (@keyValues)
		{
			if ($keyVal =~ /^\s*clone_command_line/)
			{
				$keyVal =~ s/(.*)?(\n*)/"$1 ".join(" ", @params)."$2"/e;
				$updated = "true";
				last;
			}
		}
		if ($updated eq "false")
		{ # clone-command-line flag not set yet in cs.properties. Set now.
			@keyValues[scalar(@keyValues)] = "clone_command_line= ".join(" ", @params);
		}
		# now dump the changed contents into cs.properties.
                open(CS_PROPS, ">$csProperties") || die " Cannot open file $csProperties for write. Reason: $!\n";
		print CS_PROPS @keyValues;
		close(CS_PROPS);
	}
	else
	{
		print "cs.properties not found in Oracle home.\n";
		exit(254);
	}
}

my @params = parseParams();
my $oracleHomeLoc = shift(@params);
updateCSProperties($oracleHomeLoc, @params);
print "cs.properties updated.\n";

