#!/bin/sh -u

# tape_aid_wrapper is what the flip_tab and take_out scripts are linked to.

if [ "${1:-}" = "-d" ]; then debug=1; shift; fi

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

usage() { case $script in
	    flip_tab | take_out)
	       echo "Usage: login as enstore to d0ensrv4[n], stkensrv4[n], or cdfensrv4[n]"
	       ;;
	    tape_aid_wrapper)
	       echo "Usage: run as flip_tab or take_out"
	       ;;
	  esac
	  case $script in
	    *flip_tab)
	       echo "       enter $script [[un]lock]"
	       ;;
	    *take_out)
	       echo "       enter $script [shelve|remove|reload|xfer]"
	       ;;
	  esac
	}

check_work() { local action1 work1
	       while read action1 work1
	       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
lock	${robot}_write_protect_work
unlock	${robot}_write_permit_work
shelve	${robot}_shelf_volumes_work
remove	${robot}_purge_volumes_work
reload	${robot}_refit_barcode_work
xfer	${robot}_xfer_volumes_work
EOD

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

YesNo() { local ans
	  until read -p "$1 [y/n] " ans && expr "$ans" : '[NYny]' >/dev/null
	  do
	    echo "Please answer Y or N" >/dev/stderr
	  done
	  case $ans in
	    y*|Y*) echo Yes;;
	    n*|N*) echo No;;
	  esac
	}

script=`basename $0`
case $script in
  flip_tab | take_out)
     ;;
  *) usage
     exit 1
     ;;
esac

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

node=`hostname -s`

gang=`gang`

# should use config server to determine media changer host
case $node in
  ${gang}srv4 | ${gang}srv4n)
    ;;
  *)
    usage
    exit 1
    ;;
esac

until [ -n "${location:-}" ]; do
  echo
  echo "Where are you ?  Choose"
  case $gang in
    d0en)
      echo " 1) GCC  if you are in GCC"
      echo " 2) FCC2 if you are on the 2nd floor in FCC"
      echo " 3) Quit if you are somewhere else"
      locations="GCC FCC2"
      ;;
    stken)
      echo " 1) GCC  if you are in GCC"
      echo " 2) FCC2 if you are on the 2nd floor in FCC"
      echo " 3) Quit if you are somewhere else"
      locations="GCC FCC2"
      ;;
    cdfen)
      echo " 1) GCC  if you are in GCC"
      echo " 2) FCC2 if you are on the 2nd floor"
      echo " 3) Quit if you are somewhere else"
      locations="GCC FCC2"
      ;;
  esac
  echo
  EOF=1
  select location in $locations Quit; do EOF=0; break; done
  [ $EOF -gt 0 ] && exit
done

case ${gang}@${location} in
  *en@FCC2)  # some locations unambiguously define a library
     robot=8500F1
     sun=fntt2
     case ${gang} in
       cdfen)
	  icap="1,1,0"       # acs 1, lsm 1, (rail 2), cap A
	  ocap="1,5,0"       # acs 1, lsm 5, (rail 2), cap A
	  ;;
       d0en)
	  icap="1,1,0"       # acs 1, lsm 1, (rail 2), cap A
	  ocap="1,5,0"       # acs 1, lsm 5, (rail 2), cap A
	  ;;
       stken)
	  icap="1,1,0"       # acs 1, lsm 1, (rail 2), cap A
	  ocap="1,5,0"       # acs 1, lsm 5, (rail 2), cap A
	  ;;
       *) exit 1
	  ;;
     esac
     ;;

  *en@GCC)		# disambiguate the libraries at GCC
     until [ -n "${lib:-}" ]; do
       echo
       echo "Which library are you working with ?  Choose"
       case $gang in
	 cdfen|d0en|stken)
	   echo " 1) G1 if you are working with the SL8500s in front"
	   echo " 2) GS if you are working with the SL8500-6 in the rear"
	   echo " 3) Quit if you are doing something else"
	   libs="G1 GS"
	   ;;
       esac
       echo
       EOF=1
       select lib in $libs Quit; do EOF=0; break; done
       [ $EOF -gt 0 ] && exit
     done
     case ${lib} in
       G1)
	  robot="8500G1"
	  icap="0,1,0"       # acs 0, lsm 1, (rail 2), cap A
	  ocap="0,5,0"       # acs 0, lsm 5, (rail 2), cap A
	  sun="fntt1"
	  ;;
       GS)
	  robot="8500GS"
	  icap="2,1,0"       # acs 2, lsm 1, (rail 2), cap A
	  ocap="2,1,0"       # acs 2, lsm 1, (rail 2), cap A
	  sun="fntt1"
	  ;;
       *) exit 1
	  ;;
     esac
     ;;

  *) exit 1
     ;;

esac

# take_out needs the volume clerk - find it thru the config server
if echo $script | grep 'take_out' > /dev/null; then
  vcDict=`enstore conf --show volume_clerk`
  clerk=`python -c "print $vcDict['host']"`
  [ ${debug:-0} -gt 0 ] && echo "Volume Clerk host is $clerk"
fi

case $script in
  flip_tab)
     action=${1:-"lock"}
     case $action in
       lock)
	  work=$HOME/isa-tools/${robot}_write_protect_work
	  prot=on
	  ;;
       unlock)
	  work=$HOME/isa-tools/${robot}_write_permit_work
	  prot=off
	  ;;
       *) usage
	  exit 1
	  ;;
     esac
     ;;
  take_out)
     action=${1:-"shelve"}
     case $action in
       shelve)
	  work=$HOME/isa-tools/${robot}_shelf_volumes_work
	  ;;
       reload)
	  work=$HOME/isa-tools/${robot}_refit_barcode_work
	  ;;
       remove)
	  work=$HOME/isa-tools/${robot}_purge_volumes_work
	  . $ENSTORE_DIR/sbin/gettkt
	  ;;
       xfer)
	  work=$HOME/isa-tools/${robot}_xfer_volumes_work
	  ;;
       *) usage
	  exit 1
	  ;;
     esac
     ;;
esac

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

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
      prompt="There are $rem groups to $action. Proceed?"
   else
      prompt="There is one group to $action. Proceed?"
   fi
   case `YesNo "$prompt"` in
     Yes)
       msg="Starting $script $action $robot on $node."
       if [ ${debug:-0} -eq 0 ]; then
	  echo "$msg" | mail -s "$gang tape aid work" ssa-auto@fnal.gov
       else
	  echo "$msg"
       fi
       ;;
     *)
       check_work
       exit
       ;;
   esac
fi

if [ ${debug:-0} -gt 0 ]; then
   check_work
   exit		# quit before we cause real trouble
fi

# Retain history of failures, usually due to a tape busy in a drive
# as these will need manual intervention.
logDir=$HOME/isa-tools/log
[ ! -d $logDir ] && mkdir $logDir
output=$logDir/${script}.${action}.${robot}.output-`date +%Y%m%d.%H%M`

# reload is advertised as a take_out function, but implemented by flip_tab
case $action in
  reload)
    runScript=flip_tab
    ;;
  *)
    runScript=$script
    ;;
esac

case $robot in
  9310 | 8500*)
    api=acsls
    ;;
esac

. $ENSTORE_DIR/src/${runScript}_${api}.sh
