#!/bin/sh
exec  >>/tmp/CDF_migrate2.`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

status=/data1/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

sp=0
snooze=60
while [ ! -r $copy ]; do
    if [ -r $done ]; then
       echo `date` $tape already finished. $done exists
       continue
    fi
    if [ $sp -eq 0 ]; then
      echo `date` Waiting for $tape to be ready to copy.
      sp=1
    fi
    sleep $snooze
done
if [ -r $done ]; then
    echo `date` $tape already finished. $done exists
    continue
fi

#echo `date` Starting copy to B tape for $tape
#echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -b $tape 2>&1"
#             $ENSTORE_DIR/test/CDF_migration/migrate_tape -b $tape 2>&1
#rcb=$?
##if [ $rcb -ne 0 ]; then
##    echo `date` Trouble copying to b tape - touching $stop and $halt
##    touch $stop
##    touch $halt
##    continue
##fi

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
  rcV=$?
  if [ $rcV -ne 0 ]; then
    echo `date` Trouble verifying b tape - trying again...
    echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -b $tape 2>&1"
                 $ENSTORE_DIR/test/CDF_migration/migrate_tape -b $tape 2>&1
  else
    break
  fi
done

echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -V $tape 2>&1"
             $ENSTORE_DIR/test/CDF_migration/migrate_tape -V $tape 2>&1
rcV=$?
if [ $rcV -ne 0 ]; then
    echo `date` Trouble verifying b tape - touching $stop and $halt
    touch $stop
    touch $halt
    continue
fi

echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -m $tape 2>&1"
             $ENSTORE_DIR/test/CDF_migration/migrate_tape -m $tape 2>&1
rcm=$?
if [ $rcm -ne 0 ]; then
    echo `date` Trouble verifying b metadata - touching $stop and $halt
    touch $stop
    touch $halt
    continue
fi


echo `date` "$ENSTORE_DIR/test/CDF_migration/migrate_tape -d $tape 2>&1"
             $ENSTORE_DIR/test/CDF_migration/migrate_tape -d $tape 2>&1
echo `date` Finished with $tape. touching $done
touch $done

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