#!/usr/bin/perl
#
#  $Id: sm_cmd 27945 2013-02-14 16:38:30Z teetov $
# -----------------------------------------------------------------------------
#  SM_CMD - send command to storage manager over db
#
#  usage 
#         sm_cmd OFFLINE <uuid>
#         sm_cmd ONLINE  <uuid>
#         sm_cmd SUSPEND <uuid>
#
#  Note:  
#     1. the Volume <uuid> may be present on any node in the system
#     2. Only for local disk volume name can be passed instead of uuid
#
# -----------------------------------------------------------------------------
#  Author: Alex Titov
#  QA by:
#  Copyright: videoNEXT LLC
# -----------------------------------------------------------------------------
#  
#


use warnings;
use strict;
use SKM::DB;
use File::Basename qw(dirname);
use lib dirname(__FILE__).'/../lib';            # find  SM::Config here
use SM::Config ':all';

# CONS ------------------------------------------------------------------------
my $SMCMD     =(split(/\//,$0))[-1];	        # the actual name of the prog

# VARS ------------------------------------------------------------------------
my $dbm;                                        # DB handler
my $vol=SM_Wheels(); #configs of active volumes ex: $vol->{$uuid}->{LIMIT_WRITE}
# SUBS ------------------------------------------------------------------------

sub db_master{
 eval { $dbm->disconnect() if $dbm; $dbm=''; }; # disconnect if defined
 for (my $i=1;$i<6;$i++) {
   eval {
     $dbm=DBMaster({PrintError=>0,'RaiseError' => 1});
  };
   if($@) {
     SM_LOG->logdie("Attempt $i (final). Cannot connect to master: $@") if $i>=5;
     SM_LOG->error("Attempt $i. Cannot connect to master: $@");
     SM_LOG->error('Sleep '. $i*30 . ' before next attempt');
     sleep($i*30);
   } else {
     last;                                   # exit cycle if OK
   }
 }
 $dbm->{FetchHashKeyName} = 'NAME_uc';
 $dbm->{ShowErrorStatement}=1;
 SM_LOG->debug("Connected to master db");
}

#------------------------------------------------------------------------------
# send command to the volume over db
#
#------------------------------------------------------------------------------
sub send_cmd {
    my $state=shift;
    my $uuid=shift;
    my $cmd="update SM_CST set CST='$state' where ID='$uuid'";
#    print "$cmd\n";
    $dbm->do($cmd);
}

#------------------------------------------------------------------------------
sub get_task {
 return ('') if not defined $ARGV[0];
 my $task=$ARGV[0];
 return ('') if not $task=~/^(OFFLINE|ONLINE|SUSPEND)$/;
 return ('') if not defined $ARGV[1];
 my $uuid=$ARGV[1];
 foreach(keys %$vol) {             # only for local drives
   $uuid=$_,last if /^$uuid/; # short format match found
   $uuid=$_,last if $vol->{$_}->{NAME} eq $uuid; # name matches
 }
 print "Note: '$ARGV[1]' substituted by $uuid\n" if $uuid ne $ARGV[1];

 if($uuid !~ /^\w{8}-(\w{4}-){3}\w{12}$/) {
   print STDERR "Incorrect format for uuid argument. Expected hhhhhhhh-dddd-dddd-dddd-hhhhhhhhhhhh\n";
   return '';
 }
 return ($task,$uuid);
}


# MAIN =========================================================================
 SM_LOG->info("$SMCMD starts");
 my ($task,$uuid)=get_task;
 if(not $task) {
   print "\n\nUsage:\n\t$SMCMD OFFLINE <uuid>\n\t$SMCMD ONLINE <uuid>\n\t$SMCMD SUSPEND <uuid>\n\n";
   exit 1;
 }

 eval {
 	db_master;                                        # connect to database
        send_cmd($task,$uuid) if $task=~/^(OFFLINE|ONLINE|SUSPEND)$/; 
 }; # end_eval
 if ($@) {
   print STDERR "Cannot set $task for $uuid : $@"; # double error to stderr (if run manually)
   SM_LOG->error("Cannot set $task for $uuid : $@"); 
 }
 SM_LOG->info("$SMCMD finished");
