#!/bin/ksh
#
#       mtbs	- return blocksize of next block on magtape
#	mtfile	- run unix file "magic" on magtape
#
#  10-jul-1995 jrv initial release <john.vanderpool@gsfc.nasa.gov> (fish)
#
# note: no support for rmt w/ this utility (due to dd and mt blksize)
#

if [ "${1:-}" = "-i" ]; then shift; fi
tpdev="${1:-${TAPE:-/dev/nrtape}}"
self=`basename $0`

tmpdir="${TMPDIR:-/tmp}"
tmpfile=$tmpdir/mtutils.$$


if [ ! -c $tpdev -a ! -b $tpdev ]; then		# not a device file
  echo $tpdev is not a device file
  exit 1
fi


if [ `uname` = IRIX ]; then			# use irix blksize feature

  mt -t $tpdev blksize 1>/dev/null 2>&1		# reset irix/tps bug
  if [ $? -ne 0 ]; then
    echo "mt error encountered"
    mt -t $tpdev stat
    exit 1
  fi
  bs=`mt -t $tpdev blksize 2>&1 | grep Maximum | cut -f5 -d" "`	# get maxblksz

  let MAXDMASZ_BYTES="(1024-1)*4*1024"		# max default DMA on irix
  if [ bs -gt $MAXDMASZ_BYTES ]; then
    bs=$MAXDMASZ_BYTES
  fi

else
  bs=65533					# 64KB-3 is ok on most OS'es

fi


dd if=$tpdev of=$tmpfile count=1 bs=$bs >/dev/null 2>&1

if [ $? = 0 ]; then

  mt -t $tpdev bsr 1 >/dev/null 2>&1

  if [ $self = mtbs ]; then
    bytes=`ls -l $tmpfile | awk '{ print $5 }'`
    let mod=bytes%512
    if [ $mod -eq 0 ]; then
      let blocks=bytes/512
      echo bytes=$bytes blocks=$blocks
    else
      echo bytes=$bytes
    fi

  elif [ $self = mtfile ]; then
    file $tmpfile | sed "s%$tmpfile%$tpdev%"

  fi

  if [ -f $tmpfile ]; then /bin/rm $tmpfile; fi

else
 echo "dd error encountered"
 exit 1

fi
