#!/bin/sh -u

if [ "${1:-}" = "-x" ]; then set -xv; shift; fi

script=`basename $0`

usage() { echo "Usage: login as enstore to d0ensrv4 or stkensrv4"
	  echo "       enter $script [[un]lock]"
	}

check_work() { local work1 action1
	       while read work1 action1
	       do
		 if [ $work1 != $(basename $work) -a -d $(dirname $work)/$work1 ]; then
		    rem=`ls -vI \*.\* $(dirname $work)/$work1 | awk 'END {print NR}'`
		    if [ $rem -gt 1 ]; then
		       echo "`date` There are $rem groups to $action1."
		    elif [ $rem -eq 1 ]; then
		       echo "`date` There is one group to $action1."
		    fi
		 fi
	       done << EOD
adic_write_protect_work		lock
adic_write_permit_work		unlock
adic_shelf_volumes_work		shelve
adic_purge_volumes_work		remove
EOD

	       ns=`find $work -type f -name \*.done -daystart -mtime -1 -print | awk 'END {print NR}'`
	       nf=`find $work -type f -name \*.fail -daystart -mtime -1 -print | awk 'END {print NR}'`
	       msg="Today's $script work: $ns groups ${action%e}ed, $nf groups failed."
	       echo "`date` $msg"
	       if [ $ns -gt 0 -o $nf -gt 0 ]; then
		 enstore alarm --raise --severity "I" --root-error "$msg"
		 echo "$msg" | mail -s "`gang` tape aid work" isa-group@fnal.gov berman@fnal.gov
	       fi
	     }

[ "`whoami`" != enstore ] && usage && exit 1

node=`hostname -s`
case $node in
  stkensrv4)
     type=DECDLT
     ;;
  d0ensrv4)
     type=3480
     ;;
  *) usage
     exit 1
     ;;
esac

action=${1:-"lock"}
case $action in
  lock)
     work=$HOME/isa-tools/adic_write_protect_work
     prot=on
     ;;
  unlock)
     work=$HOME/isa-tools/adic_write_permit_work
     prot=off
     ;;
  *) usage
     exit 1
     ;;
esac

# look for work at home first, then under /
[ -d $work ] || work=/$(basename $work)

if [ ! -d $work ]; then
  echo "`date` ERROR. $work does not exist"
  exit 1
fi

cd $work

rem=`ls -vI \*.\* | awk 'END {print NR}'`
if expr $rem : 0 >/dev/null; then
   echo "`date` There are no groups to $action. Goodbye."
   check_work
   exit
else
   if [ $rem -gt 1 ]; then
      /bin/echo -n "There are $rem groups to $action. Proceed [y/n]? "
   else
      /bin/echo -n "There is one group to $action. Proceed [y/n]? "
   fi
   if read ans && expr "$ans" : '[Yy]' >/dev/null; then
      echo "Starting $script $action on $node." | mail -s "`gang` tape aid work" isa-group@fnal.gov
   else
      exit
   fi
fi

output=/tmp/${script}.${action}.output

for i in `ls -vI \*.\*`; do
  t0=`date +'%s'`
  pid=
  stat=
  # must wait for this box to finish any previous insert
  ibox=`awk 'NR == 1 {sub("^E","I",$NF); print $NF}' $i`
  eval `jobs -l | awk -v Ibox=$ibox '$0 ~ Ibox {printf "pid=%s;stat=%s",$2,$3}'`
  [ "$stat" = Running ] && wait $pid 2>&1
  echo "`date` Group $i" >> $output
  . $i |tee -a $output 2>&1
  echo
  echo
  touch $i
  t1=`date +'%s'`
  delta=`expr $t1 - $t0`
  deltam=`expr $delta / 60`
  deltas=`expr $delta % 60`
  echo That cycle took $deltam minutes $deltas seconds.
  # extract the volumes about to be entered
  set `awk '{gsub(",","\n",$(NF-1)); print $(NF-1)}' $i`
  /bin/echo -n "Have $# tapes been loaded in I/O box $ibox with tabs in ${action}ed position [y/n]? "
  if read ans && expr "$ans" : '[Yy]' >/dev/null; then
     echo "... success acknowledged"
     echo
     echo "Now updating write-protect status in enstore..."
     # set the volumes successfully entered as write-protected or write-permitted
     for vol; do
       enstore vol --write-protect-$prot $vol
     done
     mv $i ${i}.done
     secs=40
  else
     echo "... failure acknowledged"
     mv $i ${i}.fail
     secs=80
  fi
  echo
  echo "Now inserting volumes from I/O box $ibox..."
  # wait for successful insert in the background
  until dasadmin insert2 -n $ibox 2>/dev/null 1>&2; do sleep $secs; [ $secs -gt 10 ] && secs=`expr $secs / 2`; done &
  echo
  echo
  rem=`ls -vI \*.\* | awk 'END {print NR}'`
  if expr $rem : 0 >/dev/null; then
     echo "`date` There are no more groups to $action. Thank you."
     break
  else
     if [ $rem -gt 1 ]; then
       /bin/echo -n "There are $rem groups remaining. Do another [y/n]? "
     else
       /bin/echo -n "There is only one group remaining! Do it [y/n]? "
     fi
     if read ans && expr "$ans" : '[Yy]' >/dev/null; then
	continue
     else
	break
     fi
  fi
done

check_work

echo "`date` Waiting for I/O box(es) to be unloaded ..."
jobs
wait
