#!/usr/bin/perl
####################################################################
# (C) Copyright 2016-2017 Hewlett Packard Enterprise Development, LP.
# (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
# @(#) Metrocluster 3PARRC Replication start script.
# @(#) Product Name                :  HP Metrocluster 3PARRC
# @(#) Product Version             :  B.12.00.10
#
# *** Note: This file MUST NOT be edited. *****
#
# Any changes made to it will be overwritten when you upgrade to the
# next release of HP Metrocluster with 3PAR Remote Copy.
#
# Changing this file may lead to unrecoverable package startup
# and/or shutdown problems.
#
###################################################################


use warnings;
use strict;
use Env;

my $package = $ARGV[0];
my $package_dir;
my $user ;
my $array;
my $rcvg;
my $SG_PATH;
my $CMVIEWCL;
my $repl_mode;
my $cli_ssh_cmd;
my $rhel_version;
if (  -e "/etc/redhat-release" ) {
        $SG_PATH="/usr/local/cmcluster";
        $CMVIEWCL=$SG_PATH."/bin/cmviewcl";
        $rhel_version = `/bin/cat /etc/redhat-release | /bin/awk -F \"[ .]\" '{print \$7}'`; 
} else {
        $SG_PATH="/opt/cmcluster";
        $CMVIEWCL=$SG_PATH."/bin/cmviewcl";
} 

Env::import();
setupParameters();
mylog ( "Setting up the parameters");
mylog ( "user:".$user."  array:".$array."  rcvg:".$rcvg );
mylog("Replication mode is: $repl_mode");

while ( 1 ) {
	if ( -e $package_dir."/MC3PARSTARTRCVG" ) {
		mylog("Trying to start the remote copy volume group" );
		if ( packageDownInLocalNode() != 0) {
			mylog( "Package is down on local node." );
			mylog( "Exiting." );
            `/bin/rm -rf $package_dir/MC3PARSTARTRCVG`;
			exit (0);
		}
        
		my $cmd = "$cli_ssh_cmd startrcopygroup $rcvg";
                mylog("Executing the command: ".$cmd );
		my @output = `$cmd`;
		my $exit_val = $? >> 8;
                if( ($repl_mode eq "Periodic") && ( $exit_val == 0 ) ){
                     $cmd = "$cli_ssh_cmd syncrcopy $rcvg";
                     mylog("Performing the syncrcopy operation as the remotecopy volume group mode is Periodic");
                     mylog("Executing the command: ".$cmd );
                     my @output_sync = `$cmd`;
                     my $exit_val_sync = $? >> 8;
                     if( $exit_val_sync == 0 ) {
                          mylog( "Checking the Remote Copy Volume Group status.");
                          $cmd="$cli_ssh_cmd showrcopy groups $rcvg -csvtable|awk '/,Status/{getline;print \$1}'|awk 'BEGIN { FS = \",\" } ; { print \$3 }'";
                          my $grp_status=`$cmd`;
                          chomp $grp_status;
			  if( $grp_status eq "Started"){	
                             mylog( "Removing the MC3PARSTARTRCVG flag now " );
                             `/bin/rm -rf $package_dir/MC3PARSTARTRCVG`;
                             mylog("Exiting......");
                             exit(0);
			   }
                     } 
                }                
		if( ($repl_mode ne "Periodic") && ( $exit_val == 0 ) ) {

			my $ret = checkForTaskStatus(@output);
			if ( $ret == 0 ) {
				mylog( "Removing the MC3PARSTARTRCVG flag now " );
				`/bin/rm -rf $package_dir/MC3PARSTARTRCVG`;
				mylog("Exiting......");
				exit(0);
			}
		}
		sleep 60;
		
	} else {
		 mylog ( "Done starting the replication. Exiting.. ");
		 exit(0);
	}
}

sub packageDownInLocalNode {

my $hostname = `hostname`;
my @hostname_tokens = split ("\\." , $hostname );
$hostname = $hostname_tokens[0];
chomp $hostname;
my $cmd = "$CMVIEWCL -v -f line -p $package | grep node:$hostname\\|status";
my @output = `$cmd`;
my $exit_val = $? >> 1;
if ( $exit_val != 0 ) {
	mylog ( "Failed to find package status on node $hostname ");
	return 0;
}
for my $line ( @output ) {
	if ( $line =~ m/status/ ) {
		my @line_token = split ( "=" , $line );
		chomp $line_token[1];
		if (  $line_token[1] ne "down" )  {
			return 0;
		} else {
			return 1;
		}
	} else {
		next;
	}
}
mylog ( "Failed to find package status on node $hostname ");
return 0;

}


sub checkForTaskStatus {
	my @output = @_;
	mylog ( "Checking for the task Status " );
	for my $line ( @output ) {
		if ( $line =~ /task ID/ ) {
			my @task_id_arr = split ( "=" , $line );
			my $taskID = $task_id_arr[1];
			chomp $taskID;
			mylog("Task ID is ".$taskID );
			my $status = getTaskStatus($taskID);
			while ( $status == 2 ) {
				sleep( 10 );
				$status = getTaskStatus($taskID);
			}

			if ( $status == 0 ) {
				return 0;
			}else {
				return 1;
			}
		}	
	}
	return 0;	
}

sub getTaskStatus {
	my $taskID = $_[0];
	mylog ( "Getting task status");
	my $cmd = "$cli_ssh_cmd showtask -d $taskID -csvtable";
	my @output = `$cmd`;
	my $next = 0;
	for my $line ( @output ) {
		if ( $line =~ /Id,Type/ ) {
			$next = 1;
			next;
		}
		if ( $next == 1 ) {
			my @splitArray = split ("," , $line );
			if ( $splitArray[3] eq "done" ) {
				mylog("Task is done");
				return 0;
			} elsif ( $splitArray[3] eq "failed" ) {
				mylog("Task is failed");
				return 1;
			} else {
				mylog("Task is yet to be done ");
				return 2;
			}

		}
	}	
}	
			
	


sub setupParameters{


    my $host;
    my $hostName = `hostname`;
    chomp $hostName;
    my @hostNameArr = split ("\\." , $hostName );
    $host = $hostNameArr[0];

    my $dc1_host_list = `$CMVIEWCL -s config -v -f line -p $package | grep "DC1_NODE_LIST" | awk 'BEGIN { FS = "=" } ; { print \$2 }'`;
        chomp $dc1_host_list;
    $dc1_host_list=~ s/\"//g;
        my $dc2_host_list = `$CMVIEWCL -s config -v -f line -p $package | grep "DC2_NODE_LIST" | awk 'BEGIN { FS = "=" } ; { print \$2 }'`;
    chomp $dc2_host_list;
    $dc2_host_list=~ s/\"//g;
    my $dts_pkg_dir = `$CMVIEWCL -s config -v -f line -p $package | awk -F "[=]" '(\$1 ~ "dts_pkg_dir") {print \$2}'`;
    chomp $dts_pkg_dir;
    $dts_pkg_dir=~ s/\"//g;
    $package_dir = $dts_pkg_dir;
    $package_dir=~ s/(\$\w+)/$1/eeg;
    my $LOCATION="NA";
    my @dc1_node_arr = split ( " " , $dc1_host_list );
    for my $node_name ( @dc1_node_arr ) {
        my @nodeNameArr = split ("\\." , $node_name);
            $node_name = $nodeNameArr[0];
        if ( $node_name eq $host ) {
            $LOCATION="DC1";
        }
    }
    my @dc2_node_arr = split ( " " , $dc2_host_list );
    for my $node_name ( @dc2_node_arr ) {
        my @nodeNameArr = split ("\\." , $node_name);
                $node_name = $nodeNameArr[0];
         if ( $node_name eq $host ) {
                        $LOCATION="DC2";
                }
        }
    if ( $LOCATION eq "NA" )
    {
        mylog ("ERROR: Node $host is not present in either DC1_NODE_LIST or DC2_NODE_LIST");
        exit 1;
    }
    $user = `$CMVIEWCL -s config -v -f line -p $package | grep -i $LOCATION"_STORAGE_SYSTEM_USER" | awk 'BEGIN { FS = "=" }; { print \$2 }'`;
    chomp $user;
    $user=~ s/\"//g;
    $array = `$CMVIEWCL -s config -v -f line -p $package | grep -i $LOCATION"_STORAGE_SYSTEM_NAME" | awk 'BEGIN { FS = "=" }; { print \$2 }'`;
    chomp $array;
    $array=~ s/\"//g;
    $rcvg = `$CMVIEWCL -s config -v -f line -p $package | grep -i $LOCATION"_RC_VOLUME_GROUP" | awk 'BEGIN { FS = "=" }; { print \$2 }'`;
    chomp $rcvg;
    $rcvg=~ s/\"//g;
    if (! (-e "/usr/bin/cli" )) {
        $cli_ssh_cmd = "/usr/bin/ssh -l $user $array";
    } else {
        my $cli_cmd = "/usr/bin/cli -sys $array -sockssl -pwf ${SG_PATH}/conf/3parrc/$user"."_"."$array.pwf showversion -s";
        my $cli_op = `$cli_cmd`;
        my $retval = $? >> 8;
        chomp $cli_op;
        if ( ($cli_op lt "3.3.1") && ( $retval == 0 ) ) {
            $cli_ssh_cmd = "/usr/bin/cli -sys $array -sockssl -pwf ${SG_PATH}/conf/3parrc/$user"."_"."$array.pwf";
        } elsif ( ($cli_op ge "3.3.1") && ( $retval == 0) ) {
              if ( $rhel_version == 5 ) {
                $cli_ssh_cmd = "/usr/bin/cli -sys $array -sockssl -pwf ${SG_PATH}/conf/3parrc/$user"."_"."$array.pwf";
             } else { 
                $cli_ssh_cmd = "/usr/bin/ssh -l $user $array";
             }
        } 
        if ( $retval != 0 ) {
             $cli_ssh_cmd = "/usr/bin/ssh -l $user $array";
        }
    }
    my $cmd="$cli_ssh_cmd showrcopy groups $rcvg -csvtable|awk '/,Mode/{getline;print \$1}'|awk 'BEGIN { FS = \",\" } ; { print \$5 }'";
    $repl_mode=`$cmd`;
    chomp $repl_mode;
}
	
    
sub mylog {
	my $msg = $_[0];
	my $time = getTime();
	$msg = $time. "  ". $msg;
	chomp $msg;
	$msg = $msg."\n";
	open FILE , ">> $package_dir/startrep.log";
	print FILE $msg;
        close FILE;
}

sub getTime {
	my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
	my @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
	my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
	my $year = 1900 + $yearOffset;
	my $theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
	return $theTime;
}
