#!/usr/local/bin/perl
# 
# $Header: cacheBootFiles.pl 30-aug-2007.05:38:53 gaurgupt Exp $
#
# cacheBootFiles.pl
# 
# Copyright (c) 2007, Oracle. All rights reserved.  
#
#    NAME
#      cacheBootFiles.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    gaurgupt    08/30/07 - removing the caching
#    rattipal    08/08/07 - 
#    rshetty     07/30/07 - Copy boot Files to the boot directory from the
#                           repository
#    rshetty     07/30/07 - Creation
#
use strict;

my $rpmUrl = shift;
my $bootDir = shift;
print " Printing parameters\n";
print "rpmUrl = $rpmUrl\n";
print "bootDir= $bootDir\n";

copyBootFiles($rpmUrl, $bootDir);

#This subroutine copies the boot files(vmlinuz and initrd.img)
#and returns the boot directory path for the particular repository

sub copyBootFiles()
{

        my $rpmUrl = shift;
        my $bootServerPath= shift;
	
	my $bootFilesTopDir = "bootFiles";

        my $bootFileTopDirPath = $bootServerPath."/".$bootFilesTopDir;

        my $repositoryHash = `echo $rpmUrl|md5sum `;
        chomp($repositoryHash);
        $repositoryHash =~ s/\s*-//;


        my $bootFileDirPath = $bootFileTopDirPath."/".$repositoryHash;
        my $bootFileDirRelativePath = $bootFilesTopDir."/".$repositoryHash;

        print "Boot File Directory Path is $bootFileDirPath\n";

        syscmd ("mkdir -p $bootFileDirPath ;chmod -R 777 $bootFileDirPath","Failed while changing permissions of the $bootFileDirPath\n","true");

         #get boot files directly from the repository

         syscmd("cd $bootFileDirPath; wget $rpmUrl/images/pxeboot/vmlinuz -O vmlinuz","Error downloading vmlinuz","true");
         syscmd("cd $bootFileDirPath; wget $rpmUrl/images/pxeboot/initrd.img -O initrd.img","Error downloading initrd.img","true");
         syscmd("cd $bootFileDirPath; chmod 777 vmlinuz; chmod 777 initrd.img","Error changing permissions of boot files","true");



}

=head
syntax execute ($command,$errorMessage,$isexit)

This functions executes the system command $command and print $errorMessage on failure and exits if $isExit is true
=cut
sub syscmd ()
{
	 my $command = shift;
	 my $errorMessage = shift;
  	 my $isExit = shift;  # by deafult is true

     print ("Executing command: $command\n");
	 system($command);
	 my $exitStatus = $? >> 8;
	 if ($exitStatus != 0)
	 {
		  print ("Status: Failed\n");
		  print ("Error Status: $exitStatus\n");
		  if ($errorMessage) {print ("Error Message: $errorMessage\n");}

		  if ($isExit ne "false") {
    		  exit ($exitStatus);
		  }	
	 }
	 else {
		print ("Status:Succeded\n");
	 }
	 return ($exitStatus);
}
