#!/bin/sh
set -u
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

if [ -z "${1:-}" ] ; then echo `date` Usage $0 volume; exit 1; fi

# this is cheap argument processing. Must be in this order when checking. I want it cheap!
if [ "${1:-}" = "-0" ];  then RM_0=1;              shift; else RM_0=0;              fi
if [ "${1:-}" = "-a" ];  then USE_A_DRIVE=1;       shift; else USE_A_DRIVE=0;       fi
if [ "${1:-}" = "-b" ] ; then MAKE_B_COPY=1;       shift; else MAKE_B_COPY=0;       fi
if [ "${1:-}" = "-d" ] ; then DELETE_LOCAL_FILE=1; shift; else DELETE_LOCAL_FILE=0; fi
if [ "${1:-}" = "-g" ] ; then GET_MISSING_FILES=1; shift; else GET_MISSING_FILES=0; fi
if [ "${1:-}" = "-i" ] ; then IGNORE_DISK_QUOTA=1; shift; else IGNORE_DISK_QUOTA=0; fi
if [ "${1:-}" = "-l" ] ; then MAKE_LOCAL_COPY=1;   shift; else MAKE_LOCAL_COPY=0;   fi
if [ "${1:-}" = "-m" ] ; then VERIFY_META_DATA=1;  shift; else VERIFY_META_DATA=0;  fi
if [ "${1:-}" = "-r" ] ; then READ_TO_DEV_NULL=1;  shift; else READ_TO_DEV_NULL=0;  fi
if [ "${1:-}" = "-v" ] ; then VERIFY_LOCAL_COPY=1; shift; else VERIFY_LOCAL_COPY=0; fi
if [ "${1:-}" = "-V" ] ; then VERIFY_LS_B_COPY=1;  shift; else VERIFY_LS_B_COPY=0;  fi

tape=$1

delay=5

partition=/data1
local=$partition/bja

#options="--array-size=3 --buffer-size=67108864 --threaded --direct"
options="--threaded"

files=/tmp/$tape.files.$$
rm -f $files 2>/dev/null

dirs=/tmp/$tape.dirs.$$
rm -f $dirs ${dirs}.u  2>/dev/null

volume=/tmp/$tape.volume.$$
rm -f $volume  2>/dev/null

pids=/tmp/$tape.pids.$$
rm -f $pids  2>/dev/null

pidsw=/tmp/$tape.pidsw.$$
rm -f $pidsw  2>/dev/null

copy2b=/tmp/$tape.copy2b.$$
rm -f $copy2b  2>/dev/null

rc=/tmp/$tape.rc.$$
rm -f $rc  2>/dev/null
echo 0 >| $rc

clean() { rm -f $files $dirs $volume $pids $pidsw $copy2b $rc 2>/dev/null; }

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

enstore file --ls-active $tape | sed -e  's$/pnfs/fs/usr/$/pnfs/$g' >$files
#cat $files
#echo

enstore volume --vol $tape >$volume
#cat $volume
#echo

family=`grep volume_family $volume | cut -f2 -d.`

for chk in 1 2; do
  inhibit=`grep system_inhibit $volume | cut -f6 -d\' `

  if [ $inhibit = 'migrated'  ]; then
      echo `date` ERROR $tape already migrated +++++++++MIGRATION ERROR +++++++++++
      echo
      echo `date` check /tmp/finalscanXXX  on `uname -n` for errors | /usr/bin/Mail -s "$tape +++++++++MIGRATION ERROR +++++++++++" enstore-admin@fnal.gov 
      touch ${status:-/data1/status}/HALT
      touch ${status:-/data/1/status}/$tape.stop
      exit 1
  elif [ $inhibit = 'full' -o $inhibit = 'readonly' ]; then
     #echo `date` $tape has inhibit $inhibit
     break
  else
     if [ $chk -eq 2 ]; then
        echo `date` ERROR. Can not set $tape readonly
        clean
        exit 1
     else
        echo `date` Volume $tape has inhibit = $inhibit. Setting to readonly
        enstore volume --read-only $tape
     fi
  fi
done

#################################################################################################

if [ $DELETE_LOCAL_FILE -eq 1 ]; then

   cat $files | while read file; do
       lfile=$local$file
       #echo rm -f $lfile
             rm -f $lfile 2>/dev/null
   done

   clean
   exit 0
fi


###ENSTORE_SPECIAL_LIB=A-Loan; export ENSTORE_SPECIAL_LIB

#################################################################################################

if [ $MAKE_LOCAL_COPY -eq 1 -o $READ_TO_DEV_NULL -eq 1 ]; then

cat $files | while read file; do
  echo `dirname $file` >>$dirs
  if [ `echo $file | grep -c ^/pnfs/cdfen/filesets` -ne 1 ]; then
     echo echo `date` ERROR. Not configured to handle $file on $tape | /usr/bin/Mail -s "$tape +++++++++MIGRATION ERROR +++++++++++" enstore-admin@fnal.gov 
     echo echo `date` ERROR. Not configured to handle $file on $tape 
     clean
     exit 1
  fi
done
sort $dirs|uniq > ${dirs}.u
mv ${dirs}.u $dirs

cat $dirs | while read dir; do
  if [ $READ_TO_DEV_NULL -eq 0 ]; then
    disk_copy=${local}$dir
    sl=0
    if [ $IGNORE_DISK_QUOTA -eq 0 ]; then 
      while /bin/true; do
         space=`df $partition|grep /dev |awk '{print $5}'|cut -f1 -d%`
         if [ $space -lt 85 ]; then break; fi
         if [ $sl -eq 0 ]; then echo `date` LOW SPACE on $partition $space percent left... waiting; sl=1;fi
         sleep 300
       done
    fi
  else
    disk_copy=/dev/null
  fi

  if [ ! -d $disk_copy -a $READ_TO_DEV_NULL -eq 0 ]; then
    echo mkdir -p $disk_copy
         mkdir -p $disk_copy
  fi
  file_list=`grep $dir $files`
###  if [ $USE_A_DRIVE -eq 0 ]; then
###     ENSTORE_SPECIAL_LIB=A-Loan; export ENSTORE_SPECIAL_LIB
###  else
###     #unset ENSTORE_SPECIAL_LIB
###     ENSTORE_SPECIAL_LIB=A-Loan; export ENSTORE_SPECIAL_LIB
###  fi
  echo `date` encp --delayed-dismount=$delay $options $file_list $disk_copy
              encp --delayed-dismount=$delay $options $file_list $disk_copy &pid=$!
  echo $pid >> $pids
  echo
done

cat $pids | while read pid; do
    notdone=1
    print=1
    while [ $notdone -eq 1 ]; do
        present=`pstree -acpu | egrep $pid|egrep -v egrep`
        if [ $print -eq 1 ]; then
           echo `date` $pid $present
           print=0
        fi
        if [ `echo $present | grep -c encp ` -eq 0 ]; then
          notdone=0
        else
          sleep 5
        fi
    done
done

# check something!

fi

#################################################################################################

if [ $VERIFY_LOCAL_COPY -eq 1 -o $MAKE_B_COPY -eq 1 -o $GET_MISSING_FILES -eq 1 ]; then

touch $copy2b
cat $files | while read file; do
  snag=0
  lfile=$local$file
  if [ ! -r $lfile ]; then
    echo `date` ERROR: Missing $lfile tape $tape
    rm -f $copy2b  2>/dev/null
    echo 1 >| $rc
    snag=1
  else
    afile_size=`stat  $file|grep Size |awk '{print $2 }'`
    lfile_size=`stat $lfile|grep Size |awk '{print $2 }'`
    if [ $lfile_size -eq 0 -a $afile_size -ne 0 ]; then
       echo `date` ERROR: 0 length file $lfile tape $tape
       if [ $RM_0 -eq 1 ]; then
        #echo rm -f $lfile
             rm -f $lfile 2>/dev/null
       fi
       rm -f $copy2b  2>/dev/null
       echo 1 >| $rc
       snag=1
    fi
    if [ $afile_size -ne $lfile_size ]; then
       echo `date` ERROR: $file has size $afile_size, $lfile has size $lfile_size
       rm -f $copy2b  2>/dev/null
       echo 1 >| $rc
    fi
  fi
  if [ $GET_MISSING_FILES -eq 1 -a $snag -eq 1 ]; then
     dlfile=`dirname $lfile`
     if [ ! -d $dlfile ]; then
       echo mkdir -p $dlfile
            mkdir -p $dlfile
     fi
###     if [ $USE_A_DRIVE -eq 0 ]; then
###        ENSTORE_SPECIAL_LIB=A-Loan; export ENSTORE_SPECIAL_LIB
###     else
###         #unset ENSTORE_SPECIAL_LIB
###         ENSTORE_SPECIAL_LIB=A-Loan; export ENSTORE_SPECIAL_LIB
###     fi
     echo `date` encp --delayed-dismount=$delay $options $file $lfile
                 encp --delayed-dismount=$delay $options $file $lfile
  fi
done

if [ -r $copy2b ]; then echo `date` All files from $tape present on local disk; echo; fi

fi

#################################################################################################

# try to preserve the order of files when we write them to the B tape
# we need 1 job at the mover and 1 already in the queue.  submit 1, then loop

if [ $MAKE_B_COPY -eq 1 -a -r $copy2b -o $VERIFY_LS_B_COPY -eq 1 ]; then

n=0
cat $files | while read file; do
  n=`expr $n + 1`
  lfile=$local$file
  prefix=`echo $file | cut -f5 -d/`
  bfile=`echo $file | sed -e "s#/pnfs/cdfen/filesets/$prefix/#/pnfs/cdfen/filesets/.B_$prefix/#"`
  bdir=`dirname $bfile`
  if [ $VERIFY_LS_B_COPY -eq 1 ]; then
     if [  ${VERIFY_LS_B_COPY_LS:-0} -eq 1 ]; then
        ls -l $bfile
     else
        if [ ! -r $bfile ]; then
           echo `date` ERROR: Missing $lfile tape $tape
           echo 1 >| $rc
        else
           bfile_size=`stat  $bfile|grep Size |awk '{print $2 }'`
           lfile_size=`stat $lfile|grep Size |awk '{print $2 }'`
           if [ $bfile_size -eq 0 -a $lfile_size -ne 0 ]; then
              echo `date` ERROR: 0 length file $bfile tape $tape
	      echo `date` issuing rm $bfile
	                          rm $bfile
              echo 1 >| $rc
           elif [ $bfile_size -ne $lfile_size ]; then
              echo `date` ERROR: $bfile has size $bfile_size, $lfile has size $lfile_size
	      echo rm $bfile
	      echo `date` issuing rm $bfile
	                          rm $bfile
              echo 1 >| $rc
           fi
        fi
     fi
  else
    if [ ! -d $bdir ]; then
       echo mkdir -p $bdir
            mkdir -p $bdir
    fi
    (cd $bdir; 
     enstore pnfs --file-family $family; 
     bn_lib=`enstore pnfs --library`; 
     if [ "${bn_lib:-x}" != "CDF-Migration" ]; then 
       echo `date` LIBRARY WRONG. Read "${bn_lib:-x}" but needs to be "CDF-9940B" for $bdir $family   touching HALT to stop; 
       echo `date` LIBRARY WRONG. Read "${bn_lib:-x}" but needs to be "CDF-9940B" for $bdir $family   touching HALT to stop  on `uname -n` for errors | /usr/bin/Mail -s "$tape +++++++++MIGRATION ERROR +++++++++++" enstore-admin@fnal.gov 
       touch ${status:-/data1/status}/HALT; 
       touch ${status:-/data1/status}/$tape.stop; 
       exit 1; 
     fi )
###    ENSTORE_SPECIAL_LIB=CDF-Migration
###    export ENSTORE_SPECIAL_LIB
    echo `date` $n encp --delayed-dismount=$delay $options $lfile $bfile
                   encp --delayed-dismount=$delay $options $lfile $bfile &pid=$!
    echo $pid >> $pidsw
    sleep 5 # clearly delineate encps for time ordering
  fi
done

if  [ $MAKE_B_COPY -eq 1 -a -r $copy2b  ]; then

    cat $pidsw | while read pid; do
        notdone=1
        print=1
        while [ $notdone -eq 1 ]; do
            present=`pstree -acpu | egrep $pid|egrep -v egrep`
            if [ $print -eq 1 ]; then
               echo `date` $pid $present
               print=0
            fi
            if [ `echo $present | grep -c encp ` -eq 0 ]; then
               notdone=0
            else
               sleep 5
            fi
        done
    done

fi
fi

#################################################################################################

if [ $VERIFY_META_DATA -eq 1 ]; then

$ENSTORE_DIR/sbin/checkAB.py -v $tape

fi

rcode=`cat $rc`
clean
exit $rcode

