#!/usr/bin/perl

# Copyright 2008-2013 Cumulus Systems Incorporated.
# All Rights Reserved.

# This file contains the code for cleanup. It is call at time of delete probe
#
# @param : 	*.Properties file
#
# @return : In case of Success, returns 0. In case of Failure, returns 1.
#
# Sample command: perl configureRaidcom.pl *.Properties

# It is used for strict compilation.
use strict;

# It helps in debugging. 	
use warnings;

# It is use to copy files
use File::Copy;

# It is use to get current date and time.
use Time::HiRes qw(gettimeofday);
use POSIX "strftime";
use Time::Local;

# This is used to create folder recursively.
use File::Path qw(mkpath);

# Set baseFolder.
my $baseFolder = '/usr/local/megha';

# This variable used to store the complete name of log file.
my $logFile;

# This variable use to store the instance number of raidcom.
my $instNum; 

# This variable use to store IpAddress of SVP [VSP/HUS-VM].
my $svpIpAdd ;

# These variables are use to store path of /etc/services file and its backup.
my $servicefile ;
my $tempServiceFile ;

# This variable is used to store the return status of function calls.
my $status = 0;

# Initialize the environment.
$status = init();
if (0 != $status)
{
    logMsg("Error: Call to init() failed.");
    goto EXIT;
}

if (! copy( $servicefile, $tempServiceFile ) )
{
	logMsg("Error: Not able to take backup of [ $servicefile ] to [ $tempServiceFile ] file.");
	$status = 1;
	goto EXIT;
}

# Run horcmshutdown.sh script for given instance
my $sysret = system("horcmshutdown.sh $instNum");
if($sysret)
{
	logMsg("Error: Not able to shutDown instance [$instNum]");
	# kill that process
	my $processID = "";
	$processID = `pidof horcmd_0$instNum`;
	my $syscmd = system("kill -9 $processID");
	if($syscmd){
		$status = 1;
		logMsg("Error: Not able to kill process [horcmd_0$instNum]");
	}
}

# Delete entry of instance number from $tempServiceFile.
if ( open(SER_FILE, "<", $tempServiceFile) )
{	
	my @serviceFileArray = <SER_FILE>;
	close (SER_FILE);
	
	if ( open(SERV_FILE, ">", $tempServiceFile) )#|| die "error in opening  $tempServiceFile file";
	{	foreach my $line (@serviceFileArray)
		{
					
			print SERV_FILE $line unless ( $line =~ m/^horcm$instNum/ );
		}
		close(SERV_FILE);
	}	
}
else{
	logMsg("Error: Not able to open file [$tempServiceFile]");
	$status = 1;
	goto EXIT;
}
# Rename tempServiceFile to seviceFile.
if (!rename($tempServiceFile, $servicefile))
{
	logMsg("Error: Not able to rename [$tempServiceFile] to [$servicefile].");
	$status = 1;
}
#delete /etc/horcm<instNum> file 
if( -e "/etc/horcm$instNum.conf")
{
	#delete .conf file
	unlink "/etc/horcm$instNum.conf" or logMsg("Error: Not able to delete [ /etc/horcm$instNum.conf ] file.");
}

EXIT:
exit $status;
# This function is used to log a message in the log file. It logs the message in the following format:
# [YYYY-MM-DD HH:MM:ss,SSS]  [SVP-<IP Address>] [Perf_Collection] <Log message>
#
# @param :
# $_[0] - Log message.
#
# @return :
#   Nothing
sub logMsg
{
    # This variable is used to store the complete path of probe specific folder in db/probe folder.
    my $svpLogFolder = "";

    # Set Eternus log folder path.
    $svpLogFolder = $baseFolder."/logs/SVPProbe";

    # If log folder does not exist then create it.
    if (!(-e $svpLogFolder))
    {
        # TODO: Check the return value of mkpath.
        mkpath($svpLogFolder);
    }

    # Get the current date and time.
    my ($seconds, $microseconds) = gettimeofday;
    my $currentTime = strftime("%Y-%m-%d %H:%M:%S", localtime($seconds));

    # Get the date from the given date and time .
    my($date, $time) = split(' ', $currentTime, 2);

    # Set the name of log file.
    $logFile = $svpLogFolder."/SVPProbe.".$date.".log";

    # Open the log file.
   if ( open(LOG_HANDLE, ">>", $logFile) )
   {
		# Read input parameters.
		my $logMsg = $_[0];

		# For getting time in a given format.
		$currentTime = "[".$currentTime.",".$microseconds."]";

		# Construct the final log message.
		my $finalMsg = $currentTime." [SVP-".$svpIpAdd."] [Probe_Deletion] ".$logMsg."\n";

		# Dump the final log message in log file.
		print LOG_HANDLE $finalMsg;

		close (LOG_HANDLE);
	}
}


# ----------------------------------------------------------------------------------------------------------------------------------------------------
# Sub-routines
# ----------------------------------------------------------------------------------------------------------------------------------------------------
# This function is used to initialize the environment to run the Perl script correctly.
#
# @affected global variables :
#   $baseFolder
#   $logFile
#   $instNum
#   $svpIpAdd
#   $servicefile
#	$tempServiceFile
#
# @return :
#   0 if Success
#   1 if Error
sub init
{
    # This variable is used to store the return value of function calls.
    my $retVal = 0;

    # Set base folder.
    $baseFolder = "/usr/local/megha";
	
	$logFile = "";

    # If number of command line arguments are not correct then quit.
    if (2 != ($#ARGV + 1))
    {
        logMsg("Error: Number of arguments to deleteRaidcomInstance.pl are not correct. Input arguments = ".($#ARGV + 1));
        $retVal = 1;

        goto EXIT;
    }

    # Get the SVP IP Addrss from command line argument.
    $svpIpAdd = $ARGV[0];
	$instNum = $ARGV[1];
    logMsg("Info: Input IP Address = [$svpIpAdd] and Instance Number = [$instNum].");

    # Set /etc/services and its backup path.
    $servicefile = '/etc/services';
	$tempServiceFile = "$baseFolder/temp/temp_services.txt";
    logMsg("Info: services file path: [$servicefile] and its backup [$tempServiceFile].");

EXIT:

    return $retVal;
}