#!/usr/bin/perl
#
#  $Id$
# -----------------------------------------------------------------------------
#  SM_RELINK - small tool re-link volume to the store 
# -----------------------------------------------------------------------------
#  Author: Alex Titov
#  QA by:
#  Copyright: videoNEXT LLC
# -----------------------------------------------------------------------------
#
# notes:
#   1. command line tool
#
# usage: 
#  sm_relink uuid


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 $APL=$ENV{APL};
my $RELINK  =(split(/\//,$0))[-1];	          # the actual name of the prog
my $SM_VER  =SM_VER;
my $DF       ='/bin/df -P';

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

# ARGS ------------------------------------------------------------------------
my $uuid=$ARGV[0];
# SUBS ------------------------------------------------------------------------

sub relink {
 my $uuid=shift;
 #------------------------------- ACTUAL CONVERT OPERATIONS
 # 1. links only /vasm/uuid/$SM_VER to /vasm/store/$SM_VER 
 # 2. reference will be replaced in /vasm/store/$SM_VER/$dev/$date/$hour if exists
 # 
 # old: /vasm/store/va-2.6.2/101/091103/10.0000->/vasm/<uuid>/va-2.6.2/101/091103/10.0000
 # new: /vasm/store/va-2.6.2/101/091103/10.0000-01->/vasm/<uuid>/va-2.6.2/101/091103/10.0000-01

 my $src  ="/vasm/$uuid/$SM_VER";
 my $store="/vasm/store/$SM_VER";

 opendir(DEV,$src) || die "Cannot read $src";
 my @dev = grep {/^a?\d+/} readdir(DEV);
 close DEV;

 foreach my $dev (@dev) { 
   mkdir("$store/$dev",0755);
   opendir(DAYS,"$src/$dev") || die "Cannot read $src/$dev";
   my @days= sort grep {/^\d{6}$/} readdir(DAYS);
   close DAYS;
   foreach my $day (@days) {
      opendir(HOURS,"$src/$dev/$day") || die "Cannot read $src/$dev/$day";
      my @hours= sort grep {/^\d\d\.\d{4}/} readdir(HOURS);
      close HOURS;
      mkdir("$store/$dev/$day",0755);
      foreach my $hour (@hours) {      # each hour looks like 12.0000 or 12.2356
#        print "ln  $src/$dev/$day/$hour $store/$dev/$day/$hour\n";
         unlink "$store/$dev/$day/$hour" if -l "$store/$dev/$day/$hour";
         symlink("$src/$dev/$day/$hour","$store/$dev/$day/$hour");
      }
   }
 }
}

# MAIN =======================================================================

if(!$uuid) {
  print "\n\nUsage:\n\t$RELINK <uuid>\n";
  exit 1;
}
if( ! -d "/vasm/$uuid" ) {
  print "ERROR: directory /vasm/$uuid is not present\n";
  exit 1;
}
`$DF /vasm/$uuid | grep -sq /vasm/$uuid`;
if($?) {
   print "ERROR: the volume $uuid is not mounted to /vasm/$uuid";
   exit 1;
}

relink($uuid);


