#!/usr/bin/perl
#
#  $Id$
# -----------------------------------------------------------------------------
#  SM_STORE - handle /vasm/store mount 
# -----------------------------------------------------------------------------
#  Author: Alex Titov
#  QA by:
#  Copyright: videoNEXT LLC
# -----------------------------------------------------------------------------
#
# sm_dblog:
# 1. Universal (Darwin,Linux) but action only done in Darwin since linux
#    uses /etc/fstab store definition
# 2. Starts from sm_engine (once!)
# 3. Check if /vasm/store is mounted. If not then find the store and mount
# 4. exit if CIRRUS (we do not need store for CIRRUS)
#
# for REQ see: Rally S623:Storage Manager TA1616: Mac adaptation
#
use warnings;
use strict;
use Data::Dumper;
use File::Basename qw(dirname);
use lib dirname(__FILE__).'/../lib';              # find  SM::Config here
use SM::Config ':all';

# CONS -------------------------------------------------------------------------
my $SMSTORE=(split(/\//,$0))[-1];	         # the actual name of the prog
my $APL    =$ENV{APL};
my $MNT    ='/vasm/store';                       # target for mount
my $DF     ='/bin/df -P';
my $MOUNT  ="sudo $APL/sm/sbin/sm_mount";        # mount by root operation

# VARS -------------------------------------------------------------------------

# SUBS -------------------------------------------------------------------------

# MAIN =========================================================================
exit 0 if $ENV{APL_MOD} eq 'CIRRUS';           # we do not need store for CIRRUS
exit 0 if $ENV{APL_MOD} eq 'SKMHA';            # we do not manage store in SKMHA

#SM_WritePid($SMSTORE);                        # do not write pid 
 SM_LOG->info("$SMSTORE starts");
 `$DF $MNT | grep -q $MNT`;                    # store is absent
 if($?) {                                       
   SM_LOG->info("$MNT has to be mounted");
   my $vols=SM_Declared;
   my $store;
   if(defined $vols->{store}) {                # explicity defined by name
     $store=$vols->{store}; 
   }else{                                      # find by USAGE
     foreach (sort %$vols) {
       $store=$vols->{$_} if defined $vols->{$_}->{USAGE} and $vols->{$_}->{USAGE} eq 'store';
     }
   }
   SM_LOG->logdie("Store is not declared\n") if !$store;
   SM_LOG->info("found store declaration $store->{conf_file}");
   SM_LOG->logdie("store declaration does not define UUID\n") if ! defined $store->{ID};
   $_=`$MOUNT $store->{ID} '' '' store 2>&1`;
   SM_LOG->logdie("cannot mount store: $_\n") if $?;
   SM_LOG->info("Store is mounted successfully");
 }else{
   SM_LOG->info("$MNT is mounted alredy");
 }
 SM_LOG->info("$SMSTORE finishes");
