#!/usr/local/bin/perl
# 
# $Header: linuxos_stage.pl 09-aug-2007.20:23:29 rattipal Exp $
#
# linuxos_stage.pl
# 
# Copyright (c) 2005, 2007, Oracle. All rights reserved.  
#
#    NAME
#      linuxos_stage.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#     Staging directive for linux os component
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    rattipal    08/09/07 - changing server path directly to cached rpm repos
#    rshetty     08/01/07 - removing the creation of Mirror repository
#    rattipal    07/29/07 - nas fix
#    rshetty     06/18/07 - setting permissions of cached RPM-repository to 777
#    spudukol    02/01/07 - modifying for OEL
#    rshetty     09/27/06 - including changes for fast provisioning and
#                           complete boot automation
#    rattipal    09/11/06 - Backport ssdas_suse_fix from main
#    rattipal    12/12/05 - Backport pshroff_bootfile_auto from main 
#    rshetty     08/10/06 - installing rpms in post section
#    rshetty     08/09/06 - To change agent version
#    rattipal    04/05/06 - http url support 
#    pshroff     11/30/05 - to support NAS mount commands for solaris as well as to use 
#                           one mount instead of three mounts in post section
#    suvmalho    09/20/05 - changing the default password encryption action to 
#                           enabled 
#    pshroff     09/03/05 - using 10.2agent RPM 
#    pshroff     08/29/05 - 
#    pshroff     08/24/05 - removing hardcoded timezone 
#    prayarot    08/21/05 - To support NAS 
#    pshroff     08/06/05 - using stagesharedmp in place of bootserver for 
#                           RPMs 
#    pshroff     07/31/05 - adding error handling exitstatus code 
#    pshroff     07/28/05 - adding oms.properties file in post section 
#    pshroff     07/24/05 - removed partitioning info
#    pshroff     07/21/05 - removing xconfig 
#    pshroff     06/30/05 - pshroff_map_shiphome
#    rbhanush    06/23/05 - removing isencrypted option 
#    rbhanush    06/10/05 - Adding more entries in kickstart
#    rbhanush    05/30/05 - Extracting rhelos.tar
#    rbhanush    05/24/05 - rbhanush_update_props
#    rbhanush    05/19/05 - Creation
# 

$ENV{PATH} = "/bin:/usr/bin:/usr/local/bin:/usr/sbin";

use strict;
use Cwd;

require "$ENV{EMDROOT}/sysman/admin/scripts/provisioning/provisionCommon.pl";

main();

sub main()
{
    my $rpm_repository_url_info_file = "rpm_repository.info";
    my $repositoryMirrorTopDir = "RPM-RepositoryMirror";
    my $rpm_repository_dir_path;
    my $rel_rpm_repos_path;

    print "Creating kickstart file\n";
    createAndAppendToKickstart("\n#Linux OS Part of Kickstart\n");
    my $stageTopDir=get_oraProperty("NAME_StageSharedMountPoint");
    
# Finding the name of OS component
    my $os_comp_path=`pwd`;
    chomp $os_comp_path;
    my $parent_path="..";
    chdir $parent_path;
    
    my $image_hw_path=`pwd`;
    chomp $image_hw_path;

   chdir $parent_path;
   chdir $parent_path;
   my $stagetopdir = `pwd`;
   chomp $stagetopdir;

    chdir $os_comp_path;
    
    my $os_toplevel_path=$stageTopDir."/OS";
    my $temp_image_hw_path=$image_hw_path."/";
    my $os_comp_guid=$os_comp_path;
    $os_comp_guid=~ s/$temp_image_hw_path//;   # This is the OS component name (OS compguid)
    my $dest_os_path=$os_toplevel_path."/".$os_comp_guid;	# Destination OS component directory <stage_top_dir>/OS/compguid

    #creating link from RPMS directory in os_component to RPMS directory in corresponding
    #staged rpm repository


    
#    if(!( -d $dest_os_path))  #disabling caching for boot automation
    {
	syscmd("mkdir -p -m 755 $os_comp_guid","","true");
	print "Extracting rhelos.tar\n";
	my $tar_extract_cmd="tar -xvf rhelos.tar -C $os_comp_guid";		# untaring to a local folder which then moved to actual place
	system($tar_extract_cmd);
	my $exitstatus = $? >> 8;
	if ($exitstatus != 0)
	{
	    print "\n Failed while untaring the OS Image Binary \n";
	    exit $exitstatus;
	}
   
     	my $rpm_repository_file_location = $os_comp_guid."/".$rpm_repository_url_info_file;
    
       #copying repository.info file to image hardware directory to be used by image-stage directive
       syscmd("cp -f $rpm_repository_file_location $image_hw_path","","true");

		
 		open (RPM_REPOS_INFO, $rpm_repository_file_location);
		my $rpm_repository_name = <RPM_REPOS_INFO>;
		my $repository_type = <RPM_REPOS_INFO>;  #This is the directory name RedHat or Enterprise
		close (RPM_REPOS_INFO);
                chomp($rpm_repository_name);
		chomp($repository_type);
		my $rpm_repository_dir = $rpm_repository_name;
		$rpm_repository_dir =~ s/(ftp|http|https)\:\/\///g;
		
		$rpm_repository_dir_path = $stagetopdir."/".$repositoryMirrorTopDir."/".$rpm_repository_dir;
                $rel_rpm_repos_path = $repositoryMirrorTopDir."/".$rpm_repository_dir;
  	        my $repositoryMirrorTopDirPath = $stagetopdir."/".$repositoryMirrorTopDir;


		#Create the soft links to base and RPMS directory
    
                syscmd("cd $os_comp_guid/LinuxOSRoot/$repository_type; rm -rf base; ln -s $rpm_repository_dir_path/$repository_type/base base","","true");
                                syscmd("cd $os_comp_guid/LinuxOSRoot/$repository_type; rm -rf RPMS; ln -s $rpm_repository_dir_path/$repository_type/RPMS RPMS","","true");

                                

	syscmd("chmod 755 -R $os_comp_guid","","true");
	if(!( -d $dest_os_path))
	{
	    syscmd("mv -f $os_comp_guid $os_toplevel_path","","true");
	}
	else
	{
	    syscmd("rm -rf $os_comp_guid","","true");
	}
    }
    syscmd("rm -f rhelos.tar","","true");
    
    #timezone
    my $osTimeZone = get_oraComponentProperty("NAME_TimeZone");
    my $useUtcClock = get_oraComponentProperty("NAME_UseUtcClock");
    my $osTimeZone_entry;
    if($useUtcClock eq "true")
    {
        $osTimeZone_entry="timezone --utc $osTimeZone \n";
    }
    else
    {
        $osTimeZone_entry="timezone $osTimeZone \n";
    }
    appendToKickstart($osTimeZone_entry);
    
    #my $dummy_passwd="rootpw --iscrypted $1$UOG2nAQn$J745.WTWWcluPTszuUgBy/";
    my $passwd= get_oraComponentProperty("NAME_RootPassword");
    
    #password encryption option
    my $passwd_encrypt= get_oraComponentProperty("NAME_RootPasswordEncrypt");
    my $passwd_entry="rootpw --iscrypted $passwd \n";
    my $passwd_encrypt_entry="authconfig --enablemd5 \n";
    if($passwd_encrypt eq "false")
    {
        $passwd_entry="rootpw $passwd \n";
        $passwd_encrypt_entry="authconfig \n";
    }
    appendToKickstart($passwd_entry);
    appendToKickstart($passwd_encrypt_entry);
    
    #text/install mode
    my $installMode = get_oraComponentProperty("NAME_InstallMode");
    
    my $textMode = "text\n";
    my $graphicMode = "\n";
    
    my $installMode_entry = ( $installMode eq "true") ? $graphicMode : $textMode;    
    appendToKickstart($installMode_entry);
    
    #Get Base URl and always relplace Stage Dir with BaseURl entry
    my $stageTopDir=get_oraProperty("NAME_StageSharedMountPoint");
    my $base_url = get_oraProperty("NAME_StageBaseUrl");
    print "\n Base URL is:$base_url\n";
    my (@url_info, $len, $count, $url_entry, $dir, $nfs_host_name, $nfs_host_dir);
    $nfs_host_dir="";
    @url_info = split /\/+/ ,$base_url ;
    $len = $#url_info;
    for($count=1;$count<=$len;$count++)
    {
        $url_entry=$url_info[$count];
        if($count ==1)
        {
            $nfs_host_name = $url_info[$count];
        }
        if($count >1)
        {
            $nfs_host_dir = $nfs_host_dir."/".$url_info[$count];
        }
    }
    #my $rel_os_path="OS/".$os_comp_guid;
    my $rel_os_path= $rel_rpm_repos_path;
    print "\n Host is:$nfs_host_name and Directory is :$nfs_host_dir\n";
    createNFSEntry($base_url,$nfs_host_name, $nfs_host_dir, $rel_os_path );
    
    $rel_os_path="OS/".$os_comp_guid;
	#Create link for ref-anaconda-ks.cfg for image directive
    my $currentfolder_cmd="pwd";
    my $currentfolder=`$currentfolder_cmd`;
    chomp $currentfolder;
    print "Current folder is: $currentfolder\n";
    
    #Remove link first
    my $remove_cmd="rm -rf ../ref-anaconda-ks.cfg";
    system($remove_cmd);
    my $exitstatus = $? >> 8;
    if ($exitstatus != 0)
    {
        print "\n Failed while removing reference kickstart file link \n";
        exit $exitstatus;
    }
    
    #Create a new link
    my $createlink_cmd="ln -sf ../../$rel_os_path/anaconda-ks.cfg ../ref-anaconda-ks.cfg";
    system($createlink_cmd);
    my $exitstatus = $? >> 8;
    if ($exitstatus != 0)
    {
        print "\n Failed while creating link for reference kickstart file \n";
        exit $exitstatus;
    }
    
    #Creating post section script
    my $rel_image_hw_path=$image_hw_path;
    $rel_image_hw_path=~ s/$stageTopDir//;
    createPostSectionFile($base_url,$nfs_host_name, $nfs_host_dir, $stageTopDir, $rel_image_hw_path, $os_comp_guid);
    #Create package definition file
    createPackageSectionFileEx($nfs_host_name, $nfs_host_dir, $stageTopDir, $rel_os_path);
    appendToKickstart("\n\n");
}

#This method creates a new file holding package section of the kickstart file. 
#package-ks.cfg will be created.
#It assumes that rpms_list.txt file is present at the same level 
#where the current perl script is present.
sub createPackageSectionFileEx()
{
    my ($nfs_host_name,$nfs_host_dir,$stage_top_dir, $rel_os_path) = @_;
    
    my ($package_file, $full_rpm_name, $rpm_entry);
    my $final_rpm_list_file = "final_rpm.list";

    #Create package-ks.cfg
    $package_file="package-ks.cfg";
    open OUT, ">$package_file" or die "Can not create rpm package file : $!" ;
    
    #Add the package header
    print OUT "\n\n%packages  --ignoredeps \n";

    my $final_rpm_list_location = $stage_top_dir."/".$rel_os_path."/".$final_rpm_list_file;
    open (FINAL_RPM_LIST, $final_rpm_list_location) or die "Could not open $final_rpm_list_location";
    my @rpms_for_kickstart = <FINAL_RPM_LIST>;
    print OUT @rpms_for_kickstart; 
    close OUT;
}



# This method creates a new file holding post section of the kickstart file. 
# post section should be
# 
# If the base url protocol is nfs then, the following content will be there in post section of the kickstart
#
# rpm --import /usr/share/rhn/RPM-GPG-KEY
# mkdir /emagent-extra
# mount <nas-server>:<nas-dir> /emagent-extra
# rpm -ivh /emagent-extra/emagent-10.2.0.0.0-1.i386.rpm --nopost
# umount /emagent-extra
# rm -rf /emagent-extra
# mkdir -p -m 777 /baremetalprov
# cp <complete path of ImageHW mounted on target>/oms.properties /baremetalprov
# cp <complete path of ImageHW mounted on target>/agent.properties /baremetalprov

# If the base url protocol is non-nfs then, the following content will be there in post section of the kickstart

# rpm --import /usr/share/rhn/RPM-GPG-KEY
# rpm -ivh <complete_url_of_emagent_rpm> --nopost
# mkdir -p -m 777 /baremetalprov
# wget <complete path of ImageHW>/oms.properties -O /baremetalprov/oms.properties
# wget <complete path of ImageHW>/agent.properties -O /baremetalprov/agent.properties



# post-ks.cfg will be created.

sub createPostSectionFile()
{
    my ($base_url,$nfs_host_name, $nfs_host_dir,$stage_top_dir, $rel_image_hw_path, $os_comp_guid) = @_;
 
my $rpmname;
#my $repos_path = "$stage_top_dir/OS/$os_comp_guid/LinuxOSRoot/RedHat/RPMS";




   
    #Create post-ks.cfg
    my $post_file="post-ks.cfg";
    my $emagent_extra_folder="/emagent-extra";
    open OUT, ">$post_file" or die "Can not create post section file : $!" ;
    
    #Add the post header
    print OUT "\n%post\n";   
    my $baremetalprov_folder="/baremetalprov"; 	
    my $current_folder = `pwd`;
    chomp $current_folder;
    
  
    #rpm --import /usr/share/rhn/RPM-GPG-KEY
    my $rpm_gpg_key="rpm --import /usr/share/rhn/RPM-GPG-KEY";
    print OUT "$rpm_gpg_key\n";
    my $complete4RpmPath = $current_folder."/../../emagent-10.2.0.0.0-4.i386.rpm";
    my $complete3RpmPath = $current_folder."/../../emagent-10.2.0.0.0-3.i386.rpm";
    my $emagent_rpm_name="emagent-10.2.0.0.0-4.i386.rpm";
    if ( -e $complete4RpmPath)
    {
        $emagent_rpm_name="emagent-10.2.0.0.0-4.i386.rpm";
    }
    elsif(-e $complete3RpmPath)
    {
        $emagent_rpm_name="emagent-10.2.0.0.0-3.i386.rpm";
    }
    
    my $mount_dir_path="";
    if($base_url=~ /^file:/  || $base_url =~/^FILE:/)
    {
	#mkdir /emagent-extra
	my $create_folder="mkdir $emagent_extra_folder";
	print OUT "$create_folder\n";
	
	$mount_dir_path= $nfs_host_name.":".$nfs_host_dir; 
	#my $mount_dir_path= (substr($base_url, (index($base_url,":")+1)));
	my $mount_entry="mount ".$mount_dir_path." ".$emagent_extra_folder;
	print OUT "$mount_entry\n";

	print OUT "mkdir -p -m 777 $baremetalprov_folder\n";		





	#cp emagent-10.2.0.0.0-1.i386.rpm  /baremetalprov
	my ($rpm_install,$stage_base_url, $emagent_rpm_entry);
	$stage_base_url=$emagent_extra_folder."/";
	$emagent_rpm_entry="cp -f ".$stage_base_url.$emagent_rpm_name." ".$baremetalprov_folder;	
	print OUT "$emagent_rpm_entry\n"; 
	my $image_hw_path = $current_folder;
	$image_hw_path =~ s/$stage_top_dir/$emagent_extra_folder/; 		
	
	my $cp_oms_prop="cp -f $image_hw_path/../oms.properties $baremetalprov_folder";
	print OUT "$cp_oms_prop\n";
	my $cp_agent_prop="cp -f $image_hw_path/../agent.properties $baremetalprov_folder";
	print OUT "$cp_agent_prop\n";
	
	my $cleanup_comment="#cleanup";
	print OUT "\n$cleanup_comment\n";
	
	my $umount="umount ".$emagent_extra_folder;
	print OUT "$umount\n"; 
	
	#rm -rf /emagent-extra
	my $rm_emagent_extra="rm -rf ".$emagent_extra_folder;
	print OUT "$rm_emagent_extra\n";
	
    } 
    
    else
    {
	my $complete_url_agentrpm=$base_url."/".$emagent_rpm_name;

	print OUT "mkdir -p -m 777 $baremetalprov_folder\n";
        my $rpm_cp_command="wget $complete_url_agentrpm -O $baremetalprov_folder/$emagent_rpm_name";
	print OUT "$rpm_cp_command\n";
	my $image_hw_url=$base_url.$rel_image_hw_path;
	my $cp_oms_prop="wget $image_hw_url/oms.properties -O $baremetalprov_folder/oms.properties";
	print OUT "$cp_oms_prop\n";
	my $cp_agent_prop="wget $image_hw_url/agent.properties -O $baremetalprov_folder/agent.properties";
	print OUT "$cp_agent_prop\n";



    }
print OUT "\n#Installing agent rpm\n";    
print OUT "rpm -ivh $baremetalprov_folder/$emagent_rpm_name --nopost\n";
print OUT "rm -rf $baremetalprov_folder/$emagent_rpm_name\n";

 
    close OUT;
}   


sub createNFSEntry()
{
    my ($base_url,$mount_nfs_host_name,$mount_nfs_host_dir,$rel_os_path) = @_;
    
    my $LinuxOSRootFolderName="LinuxOSRoot";
    
    #Get the ip address
    #my $ipaddress_cmd="hostname --ip-address";
    #my $stageserver_ip=`$ipaddress_cmd`;
    #chomp $stageserver_ip ;
    
    #Get the current folder
    #my $linuxos_path=$rel_os_path."/".$LinuxOSRootFolderName;
    my $linuxos_path=$rel_os_path;
    
    
    if($base_url=~ /^file:/ || $base_url=~ /^FILE:/)
    {
	#Create a new nfs entry
	my $imagePath=$mount_nfs_host_dir."/".$linuxos_path;
	my $nfs_entry="nfs --server $mount_nfs_host_name --dir $imagePath\n";
	
	appendToKickstart($nfs_entry);
    }
    else 
    {
	my $completeurl=$base_url."/".$linuxos_path;
	my $url_entry="url --url $completeurl";
	appendToKickstart($url_entry);
    }
}

sub appendToKickstart()
{
    my ($entry)=@_;
    
    my $ksfilename="linuxos-kickstart";
    #print "Writing entry $entry to kickstart file\n";
    
    open OUT, ">>$ksfilename" or die "Can find kickstart file" ;
    
    print OUT $entry;
    
    close OUT;
}

sub createAndAppendToKickstart()
{
    my ($entry)=@_;
    my $ksfilename="linuxos-kickstart";
    #print "Writing entry $entry to kickstart file\n";
    
    open OUT, ">$ksfilename" or die "Can find kickstart file" ;
    
    print OUT $entry;
    
    close OUT;
}

#This method removes version and release no information from the rpm package name.
#Example: Input: telnet-0.17-26 Output: telnet
sub removeVerAndRelInfo()
{
    my ($rpm_name)=@_;
    my (@rpm_info, $len, $count, $rpm_entry, $rpm_package_name);
    my (@rpm_name_no_ver);

    @rpm_info = split /-/,$rpm_name ;
    $len = $#rpm_info;


    #return the same name if not in proper name-version format
    return $rpm_name if ($len < 2) ;

    for($count=0;$count<=$len-2;$count++)
    {
    $rpm_entry=$rpm_info[$count];
    chomp $rpm_entry;
    push @rpm_name_no_ver, $rpm_entry;
    }

    $rpm_package_name = join "-",@rpm_name_no_ver;

    return $rpm_package_name;

}
 							     
=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);
}
