#! /bin/sh

#	Function:	Scan/extract multi-archive TAR tape
#	System:		HETG
#	Phase:		UTL
#	Module:		tarbatch
#	Revision:	1.1
#	Date:		06/22/95
#	Author:		pgf@space.mit.edu
#	Created:	Thu Jun 22 15:34:00 EDT 1995
#	Control:	none

USAGE="$0 [-D] [-b block] [-f tape] [-h host] [-n file] [-v] {t|x}"

args="$*" tmp=/tmp/scant$$ rc=0 tar=/bin/tar opt=bf block=126 mt=/bin/mt

export TAPE

while [ $# -gt 0 ] ; do
  case $1 in
    -D)   debug=echo ;;
    -b)   block="$2" ; shift ;;
    -b*)  block=`expr substr "$1" 3 999` ;;
    -f)   TAPE="$2" ; shift ;;
    -f*)  TAPE=`expr substr "$1" 3 999` ;;
    -h)   host="$2" ; rsh="rsh $host -n" ; shift ;;
    -h*)  host=`expr substr $1 3 999` ; rsh="rsh $host -n" ;;
    -n)   nf="$2" ; shift ;;
    -n*)  nf=`expr substr $1 3 999` ;;
    -v)   opt="v$opt" ;;
    t|x)  opt=${1}$opt ; break ;;
    *)    echo "Usage: $USAGE" 1>&2 ; exit 1 ;;
  esac
  shift
done

if [ $# -eq 0 ]; then
  echo "$0: missing 't' or 'x' flag" >&2 ; exit 1
elif [ $# -gt 1 ]; then
  echo "$0: illegal arg(s): $*" >&2 ; exit 1
fi

mt="$debug $rsh $mt -f ${TAPE=/dev/nrst0}"

if $mt rew ; then : ; else exit ; fi

case .$nf in
  .[1-9]|.[1-9][0-9]|.[1-9][0-9][0-9])
         $mt fsf `expr $nf - 1` ; n=$nf ;;
  .)     n=1 ;;
  *)     echo "Usage: $USAGE" 1>&2 ; exit 1 ;;
esac  

echo "Starting tarbatch -- HETG Tape Utility

Args: $args
Date: `date`
Host: ${host-`hostname`}
Unit: $TAPE

File: $n
"

trap "rm -f $tmp" 1 2 3 15

while true ; do
  $debug $rsh $tar $opt $block $TAPE 2>$tmp
  if [ $? -eq 0 -a -f $tmp -a ! -s $tmp ] ; then
    rc=0 ; $mt fsf
  elif egrep -s 'tar: blocksize = [0-9]*' $tmp ; then
    rc=0 ; echo -n 'warning ' ; cat $tmp ; $mt fsf
  elif egrep -s 'tar:.*read error: unexpected EOF' $tmp ; then
    echo EOF ; rc=`expr $rc + 1`
  elif egrep -s 'tar:.*read error: I/O error' $tmp ; then
    echo EOT ; rc=`expr $rc + 1`
  else
    echo "" ; cat $tmp ; break
  fi
  if [ $rc -gt 1 ] ; then
    break
  fi
  n=`expr $n + 1`
  echo "
File $n
"
done

rm -f $tmp
$mt rew
echo ""
echo "done" 1>&2

exit
