#!/bin/bash
#
#     Copyright (C) 1997 Claus-Justus Heine
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#
#      This script implements a simple contents listing for the zftape
#      package using the MTIOCVOLINFO ioctl.  For use with the
#      QIC-40/80/3010/3020 floppy-tape driver "ftape" for Linux.
#

DEFAULTTAPE=${TAPE-/dev/tape}

#
# insert better option parsing here
#
TAPEDEV=${1-${DEFAULTTAPE}}

if ! echo $TAPEDEV | grep "/dev/n"
then
    TAPEDEV=/dev/n$(basename $TAPEDEV)
fi

if ! [ -c $TAPEDEV ]
then
    echo $TAPEDEV is not a character device!  1>&2
    exit 1
fi

if ! mt -f $TAPEDEV rewind
then
    echo Could not rewind $TAPEDEV - no cartridge present?  1>&2
    exit 1
fi

echo -e "\nContents of $TAPEDEV:\n"

printf "%11s%12s%20s%20s\n" "file number" "block size" "volume size" "tape space"

trap "rm -f /tmp/$0.$$" exit

while true
do
    if ! foo=$(mt -f $TAPEDEV volinfo |cut -f 2 -d =)
    then
	echo $TAPEDEV doesn\'t seem to be a floppy tape device 1>&2
	exit 1
    fi
#
# "echo foo | read foo" will not work as the "read foo" is executed in
# another shell.
#
    echo $foo > /tmp/$0.$$
    read file blksz used usedunit size sizeunit < /tmp/$0.$$
    if ! mt -f $TAPEDEV fsf 1 > /dev/null 2>&1
    then
	echo -e "\nRemaining space: $used $usedunit"
	echo -e "Tape block size: $blksz"
	if ! mt -f $TAPEDEV rewind
	then
	    echo Rewind of $TAPEDEV failed 1>&2
	    exit 1
	fi
	exit 0
    fi
    printf "%6d          %5d  %20s%20s\n"\
    $file $blksz "$size $sizeunit" "$used $usedunit"
done
