#!/bin/sh
exec  >>/tmp/CDF_migrate1.`date +'%s'` 2>&1 <&-

set -u

if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi
if [ -z "${1:-}" ] ; then echo `date` Usage $0 '<volume|file-with-list-of-volumes>' ; exit 1; fi

if [ -r $1 ]; then
 f=$1
 removef=0
else
 f=/tmp/f.$$.`date +"%s"`
 removef=1
 rm -f $f
 echo $1 >$f
fi

cat $f | while read tape; do
echo
echo

V=`enstore vol --vol $tape`
sys_inh=`echo "$V" | grep system_inhibit|cut -f2 -d:`
lib=`echo "$V" | grep library|cut -f2 -d:`
vf=`echo "$V" | grep volume_family|cut -f2 -d:`
n=`enstore fil --ls-active $tape |wc|awk '{print $1}'`
echo `date` Starting tape $tape $sys_inh $lib $vf $n files

gotit=/tmp/$tape.gotit.$$
status=/data1/status
export status
copy=$status/$tape.copy2b
done=$status/$tape.done
stop=$status/$tape.stop
halt=$status/HALT

if [ -r $halt ]; then echo `date` ERROR: $halt exists ... trouble; exit 0; fi

if [ -r $done ]; then
    echo `date` $tape already migrated
    continue
fi

if [ -r $copy ]; then
   echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -v $tape 2>&1"
                $ENSTORE_DIR/test/CDF_migration/migrate_tape -v $tape 2>&1
   rc=$?
   if [ $rc -eq  0 ]; then
      echo `date` $tape already ready for migrating
      continue
   else
      echo `date` $tape NOT ready, but copy2b file found. doing rm $copy
      rm $copy
   fi
fi


echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -v $tape 2>&1"
             $ENSTORE_DIR/test/CDF_migration/migrate_tape -v $tape 2>&1
rc=$?
if [ $rc -eq 0 ]; then
   echo `date` $tape already ready for migrating. doing touch $copy
   touch $copy
   continue
fi

echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -l $tape 2>&1"
             $ENSTORE_DIR/test/CDF_migration/migrate_tape -l $tape 2>&1

rm -f $gotit
max_try=10
try=0
while [ $try -le $max_try ]; do
  try=`expr $try + 1`

  echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -v $tape 2>&1"
               $ENSTORE_DIR/test/CDF_migration/migrate_tape -v $tape 2>&1
  rc=$?
  if [ $rc -eq  0 ]; then
     echo `date` $tape rechecked - ready for migrating
     touch $copy
     touch $gotit
     break
  else
     echo `date` $tape NOT ready, but copy2b file found. doing rm $copy
     rm $copy
  fi

  if [ `enstore vol --vol $tape| grep -c NOACCESS` -ne 0 ]; then
      echo `date` Clearing NOACCESS from $tape assuming trouble reading
      enstore vol --clear $tape
      sleeptime=600
      echo `date` Sleeping for $sleeptime to allow tape to go back to home position
      sleep $sleeptime
  fi

  echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -0 -a -g -v $tape 2>&1"
               $ENSTORE_DIR/test/CDF_migration/migrate_tape -0 -a -g -v $tape 2>&1

done

if [ -r $gotit ]; then
    rm $gotit
    continue
else
    echo `date` FAILURE for $tape. continuing with next tape...
    continue
fi

done
if [ $removef -eq 1 ]; then rm $f; fi
