#!/usr/local/bin/perl
# 
# $Header: runAsBat.pl 11-sep-2006.11:08:02 amani Exp $
#
# runAsBat.pl
# 
# Copyright (c) 2005, 2006, Oracle. All rights reserved.  
#
#    NAME
#      runAsBat.pl - Run given file as batch script.
#
#    DESCRIPTION
#      Runs given files as batch scripts after copying them with a
#      '.bat' extension.
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    amani       09/11/06 - Backport amani_fix--5467873 from main
#    amani       08/31/06 - For bug fix 5467873
#    audupi      09/16/05 - audupi_bug-4579173
#    audupi      09/06/05 - Creation
# 
require "$ENV{EMDROOT}/sysman/admin/scripts/osm/ecmCommon.pl";
use English qw(-no_match_vars);
use File::Copy;
use File::Spec;

# Copies the files provided to have a new extension. The new extension is
# appended to the original file name. The original file is not touched, and
# new files will be in the same location as the original one. If the new file
# exists already, it is overwritten based on a flag which is passed to this
# sub-routine. If the value of the flag is "true", overwriting happens. If
# "false", there is no overwriting.
# @params the new extension (without the preceding dot ["."]), flag indicating
# if the destination file can be overwritten if already exists and array
# containing location of files to be copied.
# @return array containing names of new files.
sub copyWithNewExtension
{
	my ($extension, $overwrite, @fileList) = @_;
	my @newFiles = ();
	foreach $file (@fileList)
	{
		if ($file =~ /\.bat$/)
                { # file already has ".bat" extension. Don't copy the file again.
                        @newFiles[scalar(@newFiles)] = $file;
                        next;
                }
		$destFile = "$file.$extension";
		@newFiles[scalar(@newFiles)] = $destFile;
		if (-e $file)
		{
			next if ($overwrite eq "false" && -e File::Spec -> catfile ($destFile));
			unlink $destFile;
			copy($file, $destFile) || print "File $file could not be copied. Reason: $!\n";
		}
		else
		{
			print "File $file not found.\n";
			exit (1);
		}
	}
	return @newFiles;
}

# runs the given files as batch files.
# @param list of filenames (with the bat extension).
sub runAsBat
{
	my (@fileList) = @_;
	foreach $destFile (@fileList)
	{
		$destFile =~ s'/'\\'g;
		if (-e $destFile)
		{
			my ($volume, $destDir, $batFile) = File::Spec->splitpath($destFile);
			$destDir = "$volume$destDir";
			if ($destDir ne "")
			{
				chdir ($destDir) || die "Cannot change directory to $destDir. Reason: $!\n";
			}
			my $cmdStatus = echodo($batFile);
			if ($cmdStatus != 0)
			{
				print "Error occurred during execution of $destFile. Exit-status: $cmdStatus.\n";
				exit $cmdStatus;
			}
		}
	}
}

# prints usage for this script.
sub printUsage()
{
	print "Usage: $0 <list of files to be run as batch scripts>\n";
}

if (scalar(@ARGV) == 0)
{
	printUsage();
	exit (255);
}
runAsBat(copyWithNewExtension("bat", true, @ARGV));

