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

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

. /home/enstore/enstore/test/CDF_migration/migration-setup-enstore

set -u

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 
  files=/tmp/scan.$tape
  command=/tmp/command.$tape
  rm -f $files $command 2>/dev/null

  V=`enstore vol --vol $tape`
  lib=`echo "$V" | grep library|cut -f2 -d:`
  vf=`echo "$V" | grep volume_family|cut -f2 -d:`
  sys_inh=`echo "$V" | grep system_inhibit|cut -f2 -d:`
  n=unknown
  notallowed=`echo $sys_inh|grep -c NOTALLOWED`
  migrated=`echo $sys_inh|grep -c migrated`

  if [ $notallowed -ne 1 -a $migrated -ne 1 ]; then 
      echo `date` Starting tape $tape $sys_inh $lib $vf $n files
      echo `date` ERROR $tape wrong initial state +++++++++MIGRATION ERROR +++++++++++
      echo
      echo `date` check /tmp/finalscanXXX  on `uname -n` for errors | /usr/bin/Mail -s "$tape +++++++++MIGRATION ERROR +++++++++++" enstore-admin@fnal.gov 
      continue
  fi

  enstore fil --ls-active $tape | sed -e  's$/pnfs/fs/usr/$/pnfs/$g' > $files 2>&1
  #cat $files
  n=`wc $files|awk '{print $1}'`
  echo
  echo
  echo `date` Starting tape $tape $sys_inh $lib $vf $n files
  
  echo "encp --delayed=3 --priority=300000 "          >> $command
  cat $files | while read f; do
    echo $f " " >>$command
  done
  echo "/dev/null" >>$command
  
  cmd=`cat $command`
  rm -f $command $files 2>/dev/null

  #echo `date` $cmd
  echo `date` encp \"$n files\" /dev/null
  eval        $cmd 2>&1
  rc=$?
  if [ $rc -ne 0 ]; then
      echo `date` ERROR $tape bad return code  +++++++++MIGRATION ERROR +++++++++++
      echo `date` check /tmp/finalscanXXX  on `uname -n` for errors | /usr/bin/Mail -s "$tape +++++++++MIGRATION ERROR +++++++++++" enstore-admin@fnal.gov 
  else
      echo `date` $tape All files read
  fi

done

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