#!/bin/sh -u

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

script=`basename $0`

usage() { echo "Usage: login as enstore to d0ensrv4, stkensrv4, or cdfensrv4"
	  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
write_protect_work	lock
write_permit_work	unlock
shelf_volumes_work	shelve
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)
     icap="0,1,0"
     ocap="0,0,0"
     sun=fntt
     ;;
  d0ensrv4)
     icap="1,1,0"
     ocap="1,0,0"
     sun=fntt
     ;;
  cdfensrv4)
     icap="0,0,0"
     ocap="0,1,0"
     sun=fntt2
     ;;
  *) usage
     exit 1
     ;;
esac

action=${1:-"lock"}
case $action in
  lock)
     work=$HOME/isa-tools/write_protect_work
     prot=on
     ;;
  unlock)
     work=$HOME/isa-tools/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

if [ "$icap" != "$ocap" ]; then
  /usr/bin/rsh $sun -l acsss "echo set cap mode automatic $icap '\r' logoff | bin/cmd_proc -l -q 2>/dev/null"
fi

for i in `ls -vI \*.\*`; do
  t0=`date +'%s'`
  echo "`date` Group $i" >> $output
  . $i |tee -a $output 2>&1
  echo
  echo
  if [ "$icap" = "$ocap" ]; then
    /usr/bin/rsh $sun -l acsss "echo set cap mode automatic $icap '\r' logoff | bin/cmd_proc -l -q 2>/dev/null"
    echo
    echo
    /bin/echo -n "Press Enter when all tapes have been loaded with tabs in ${action}ed position"
    read ans
    while /bin/true; do
      cap=`/usr/bin/rsh $sun -l acsss "echo q cap $icap '\r' logoff | bin/cmd_proc -l -q 2>/dev/null"`
      capstate=`echo $cap | sed -e 's#.*automatic ##' | cut -f1 -d\ `
      if [ "$capstate" = "available" ]; then break; fi
      echo "`date` Waiting for cap to be unloaded..."
      sleep 5
    done
    /usr/bin/rsh $sun -l acsss "echo set cap mode manual $icap '\r' logoff | bin/cmd_proc -l -q 2>/dev/null"
    echo
    echo
  fi
  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 '{split($0,vols); for (v in vols) if (vols[v] ~ /^[[:upper:]]+[[:digit:]]+$/) print vols[v]}' $i | sort`
  /bin/echo -n "Have $# tapes been loaded in cap $icap 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
  else
     echo "... failure acknowledged"
     mv $i ${i}.fail
  fi
  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

if [ "$icap" != "$ocap" ]; then
  msgflag=
  while /bin/true; do
    cap=`/usr/bin/rsh $sun -l acsss "echo q cap $icap '\r' logoff | bin/cmd_proc -l -q 2>/dev/null"`
    capstate=`echo $cap | sed -e 's#.*automatic ##' | cut -f1 -d\ `
    if [ "$capstate" = "available" ]; then break; fi
    if [ -z "$msgflag" ]; then
      echo "`date` Waiting for cap to be unloaded ..."
      msgflag=done
    fi
    sleep 5
  done
  /usr/bin/rsh $sun -l acsss "echo set cap mode manual $icap '\r' logoff | bin/cmd_proc -l -q 2>/dev/null"
fi
