#!/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) FCCM if you are on the mezzanine in FCC"
      echo " 3) FCC2 if you are on the 2nd floor in FCC"
      echo " 4) Quit if you are somewhere else"
      locations="GCC FCCM FCC2"
      mezz_acs=1
      ;;
    stken)
      echo " 1) GCC  if you are in GCC"
      echo " 2) FCCM if you are on the mezzanine in FCC"
      echo " 3) FCC2 if you are on the 2nd floor in FCC"
      echo " 4) Quit if you are somewhere else"
      locations="GCC FCCM FCC2"
      mezz_acs=0
      ;;
    cdfen)
      echo " 1) GCC  if you are in GCC"
      echo " 2) FCCM if you are on the mezzanine in FCC"  # CDF-9940B-D0 library is in d0en silo
      echo " 3) FCC2 if you are on the 2nd floor"
      echo " 4) Quit if you are somewhere else"
      locations="GCC FCCM FCC2"
      mezz_acs=1                # Same as d0en
      ;;
  esac
  echo
  EOF=1
  select location in $locations Quit; do EOF=0; break; done
  [ $EOF -gt 0 ] && exit
done

# flag for cdfen 9940B tapes in d0en silo
CDFinD0=0

# some locations unambiguously define a library
case ${gang}@${location} in
  *en@GCC)
     robot="8500G1"
     icap="0,9,0"	# library 2, lsm 9, rail 2, cap A
     ocap="0,5,0"	# library 3, lsm 5, rail 2, cap A
     sun="fntt-gcc"
     ;;

  d0en@FCCM|stken@FCCM)
     robot="9310"
     icap="$mezz_acs,1,0"
     ocap="$mezz_acs,0,0"
     sun=fntt
     ;;

  cdfen@FCCM)    # CDF-9940B-D0 -- CDF overflow into D0en silo, but in cdfen enstore instance
     robot="9310"
     icap="$mezz_acs,1,0"
     ocap="$mezz_acs,0,0"
     sun=fntt2
     CDFinD0=1
     ;;

  *en@FCC2)		# disambiguate the libraries on FCC2
     until [ -n "${lib:-}" ]; do
       echo
       echo "Which library are you working with ?  Choose"
       case $gang in
	 d0en|stken)
	   echo " 1) 8500 if you are working with the SL8500"
	   echo " 2) Quit if you are doing something else"
	   libs="8500"
	   ;;
	 cdfen)
	   echo " 1) 9310 if you are working with the silos"
	   echo " 2) 8500 if you are working with the SL8500"
	   echo " 3) Quit if you are doing something else"
	   libs="9310 8500"
	   ;;
       esac
       echo
       EOF=1
       select lib in $libs Quit; do EOF=0; break; done
       [ $EOF -gt 0 ] && exit
     done

     case ${gang}@${location}.${lib} in
       *en@FCC2.8500)
	  robot="8500F1"
	  icap="1,5,0"       # library 2, lsm 5, rail 2, cap A
	  ocap="1,1,0"       # library 1, lsm 1, rail 2, cap A
	  sun="fntt2"
	  ;;

       cdfen@FCC2.9310)
	  robot="9310"
	  icap="0,1,0"
	  ocap="0,0,0"
	  sun=fntt2
	  ;;

       *) 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)
	 # Keep cdfen tapes in d0en silo in separate work directory
	 if [ $CDFinD0 -eq 1 ]
	 then
	     work=$HOME/isa-tools/${robot}_CDFinD0_shelf_volumes_work
	 else
	     work=$HOME/isa-tools/${robot}_shelf_volumes_work
	 fi
	  ;;
       reload)
	  work=$HOME/isa-tools/${robot}_refit_barcode_work
	  ;;
       remove)
	  work=$HOME/isa-tools/${robot}_purge_volumes_work
	  . $HOME/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
