#use lib 'perl5';
#use lib 'perl5/site_perl';
#use lib 'perl5/site_perl/5.10.0';
#use lib 'perl5/site_perl/5.10.0/i386-linux-thread-multi';
use XML::DOM;
use XML::XPath;
use Cwd 'abs_path';
use File::stat;

$command=$];
print "\n";
print "Dell Bundle Execution Script v1.0\n";
print "Copyright Dell Inc. 2009\n";
print "Perl.Version: " .$command;
print "\n";
print "\n";

#check arguments
#add command line arguments into an array to check the length.
$nElements=$#ARGV + 1;

if ( $nElements != 2 )
{
	
	print  "This program is a sample of a script that will execute a Dell Linux Bundle in a Linux environment\n";
	print "Usage: perl BundleExec.pl <RepositoryFile> <BundleID>\n";
	exit
}

$strRepositoryFile=$ARGV[0];
$strBundleID=$ARGV[1];

#reate xml parser
$xParser = XML::DOM::Parser->new();

#load xml
$xCatalog = $xParser->parsefile($strRepositoryFile);
$xPath = XML::XPath->new(filename => $strRepositoryFile);

@arrBundleFiles = GetBundleFileList($strBundleID, $xPath);

$strBaseLoc = CalculateBaseLocation($strRepositoryFile, $xCatalog);

$strArguments = "/s /l=" . LogLocation($strBundleID);

ExecuteDups($xPath,$strBaseLoc,$strArguments,@arrBundleFiles);

sub DateTimeString
{
	@timeData = localtime(time);
	#DataTime month.day.year_hour.minutes.seconds
	$strSafeDate = @timeData[4] .".".@timeData[3].".".(@timeData[5] + 1900)."_".@timeData[2].".".@timeData[1].".".@timeData[0] ;
	print "The Time Is: " . $strSafeDate."\n";
	return $strSafeDate;
}

sub LogLocation
{
	($strBundleId) = @_;
	
	my $strLogfile = $strBundleId . "_" . DateTimeString() . ".log";
	my $strAbsPath = abs_path()."/".$strLogfile."\n";
	
	print "Log Location: " . $strAbsPath."\n";
	
	return $strLogfile;
}

sub GetBundleFileList
{
	($strBundleId, $xmlPath) = @_;
	
	my $strPath='//Manifest/SoftwareBundle[@bundleID="' . $strBundleId . '"]/Contents/Package';
	
	my $nodeSet = $xmlPath->find($strPath);
        #check if the object returned is a node set.
	if (!$nodeSet->isa('XML::XPath::NodeSet')) 
	{
                print "Bundle Not Found or Xml is Badly Formed...Exiting. \n";
                exit;
        }
	#get the package or files size.
	
	my $packageSize = $nodeSet->size();

	#check if there is something in the package/bundle.
	if($packageSize <= 0)
	{
		print "Bundle Not Found or Xml is Badly Formed...Exiting. \n";
                exit;
	}
	#define an array upto the number of files.
	my @arrFiles = (0 .. $packageSize-1);
	my $index = 0;
	#loop through the nodes to get the file names.
	foreach  $node($nodeSet->get_nodelist)
	{
		#store file name in the array.
		@arrFiles[$index]  = $node->getAttribute("path");
		#print @arrFiles[$index];
		$index = $index + 1;
	}
	return @arrFiles;
}

sub CalculateBaseLocation
{
	#populate parameters
	($strCatalogURI, $xmlCatalog ) = @_;
	
	#get absolute path to the directory
	my $strPath = abs_path($strCatalogURI);
	
	#extract the folder path
	$fileNamePos = rindex($strPath,"/");
	my $strPath = substr($strPath,0,$fileNamePos);
	
	#get value of baselocation attribute
	$strBaseLocation =  $xmlCatalog->getDocumentElement()->getAttribute("baseLocation");
	
	#return baselocation from xml file if it is not empty else return the folder path
	if( length($strBaseLocation)>0)
	{
		return $strBaseLocation;
	}
	else
	{
		return $strPath;
	}
}

sub ExecuteDups
{	
	($xmlPath, $strBaseLocation, $strArgs,@arrFileNames)=@_;
	
	print "Base Location = ".$strBaseLocation."\n";
	print "Executing DUP files\n";
		
	my $strPath = "//Manifest/SoftwareComponent";
	my $nodeSet = $xmlPath->find($strPath);
        
	#check if the object returned is a node set.
	
	if (!$nodeSet->isa('XML::XPath::NodeSet')) 
	{
                print "Bundle Not Found or Xml is Badly Formed...Exiting. \n";
                exit;
        }
	
	foreach  $node($nodeSet->get_nodelist)
	{
		#create the full path to file.
		$relativePath = $node->getAttribute("path");
		$fullPath = $strBaseLocation ."/". $relativePath;
		#check if the file is present in the bundle
		if(FileInList($fullPath,@arrFileNames) == 1)
		{
			@fileStat = stat($fullPath);
			if ( @fileStat[0] eq "" )
			{
				print "Error: File Not Found - ".$fullPath."\n";
			}
			else
			{
				print "Executing DUP: " .$fullPath."\n";
				ExecuteDUP($fullPath,$strArgs);
			}
		}
	}
}

# for info on DUP command line,:
# http://support.dell.com/support/edocs/software/smdup/dup55/en/ug/windows/3cliref.htm#wp1044974

sub ExecuteDUP 
{
	($strDUPURI, $strArgs) = @_;
	#system("/bin/chmod +x ".$strDUPURI);
	system("\"".$strDUPURI."\"");
	#WScript.Echo "Executing: " + strDUPURI
	#Set wshShell = WScript.CreateObject("WScript.shell")
	#wshShell.run """" + strDUPURI + """ " + strArguments, 7, true
	#Set wshShell = nothing
}

sub FileInList
{
	($strFileName, @arrFileNameList) = @_;
	#get the file name
	$fileNamePos = rindex($strFileName,"/");
	
	$strFile = substr($strFileName,$fileNamePos+1,length($strFileName));
	#check file name in the list
	foreach $str(@arrFileNameList)
	{
		if($str eq $strFile)
		{
			return 1;
		}
	}
	return 0;
}

