#!/bin/sh
if [ $# -ne 0 ]
then 
     case $1 in
     	-d) readflag=false
            density=1600
	    recsize=80
	    blocksize=800
	    forv="f"
	    aore="a"

##########  LABEL CODE ##########
	    label="n"
##########  END OF LABEL CODE ###

	    fname="foo";;
	 *) echo "usage:  tapedd [-d]" 1>&2
	    exit 1;;
      esac
else readflag=true
fi

echo Welcome to tape dd

if $readflag
then

while true
do
	echo
	while true
	do
		echo -n "Is the tape 1600 or 6250 bpi [ 1600 ] ? > "
		read density
		if [ -z "$density" ]
		then density=1600
		     break
		elif [ $density -eq 1600 -o $density -eq 6250 ]
		then break
		else echo Cannot handle density of $density bpi 1>&2
		fi
	done

	while true
	do
		echo -n "How many characters per block [ 800 ] ? > "
		read blocksize
		if [ -z "$blocksize" ]
		then blocksize=800
		     break
		elif [ $blocksize -lt 1 ]
		then echo "Blocksize must be a numerical value greater \
than zero!" 1>&2
		else break
		fi
	done

	while true
	do
		echo -n "Fixed or variable record lengths (f or v) [ f ] ? > "
		read forv
		if [ -z "$forv" ]
		then forv="f"
		     break
		elif [ "$forv" != "f" -a "$forv" != "v" ]
		then echo Please answer f or v! 1>&2
		else break
		fi
	done

	while true
	do
		if [ $forv = "v" ]
		then recsize=80
		     break
		fi
		echo -n "How many characters per record [ 80 ] ? > "
		read recsize
		if [ -z "$recsize" ]
		then recsize=80
		     break
		elif [ $recsize -lt 1 ]
		then echo "Record length must be numerical value greater \
than zero!" 1>&2
		else break
		fi
	done

	while true
	do
		echo -n "Is the tape ascii or ebcdic (a or e) [ a ] ? > "
		read aore
		if [ -z "$aore" ]
		then aore="a"
		     break
		elif [ "$aore" != "a" -a "$aore" != "e" ]
		then echo Unknown format $aore 1>&2
		else break
		fi
	done


##########  LABEL CODE ##########
	while true
	do 
		echo -n "Is the tape labeled (y or n) [ n ] ? > "
		read label
		if [ -z "$label" ]
		then label="n"
		     break
		elif [ "$label" = "n" -o "$label" = "y" ]
		then break
		else echo Please answer y or n! 1>&2
		fi
	done
##########  END OF LABEL CODE ###
	
	echo -n "What base name do you wish filenames to default to \
[ foo ] ? > "
	read fname
	if [ -z "$fname" ]
	then fname="foo"
	fi
	
# display information read and give user chance to fix
	echo
	echo Summary of information:
	echo
	echo density $density
	echo blocksize $blocksize characters
	if [ "$forv" = "f" ]
	then echo fixed length records
	     echo recordsize $recsize characters
	else echo variable length records
	fi
	if [ "$aore" = "a" ]
	then echo ascii format
	else echo ebcdic format
	fi

##########  LABEL CODE ##########
	if [ "$label" = "n" ]
	then echo no label
	else echo labeled
	fi
##########  END OF LABEL CODE ###

	echo default base file name:  $fname
	echo

	while true
	do 
		echo -n "Is this information correct (y or n) [ y ] ? > "
		read yorn
		if [ "$yorn" = "n" ]
		then break
		elif [ "$yorn" = "y" -o -z "$yorn" ]
		then break 2
		else echo Please answer y or n! 1>&2
		fi
	done
done
fi

# message to keep users informed
echo Entering command loop...
# set up dd vars
	
ifile="/dev/nrmt$density"
iflag="if=$ifile"
ofile="/tmp/tapedd$$"
oflag="of=$ofile"
woflag="of=$ifile"
ibsflag="ibs=$blocksize"
obsflag="obs=$blocksize"
if [ "$forv" = "f" ]
then rcbsflag="conv=unblock cbs=$recsize"
     wcbsflag="conv=block cbs=$recsize"
else rcbsflag=""
     wcbsflag=""
fi
if [ "$aore" = "a" ]
then rchflag=""
     wchflag=""
else rchflag="conv=ascii"
     wchflag="conv=ebcdic"
fi
fcount=1
ef1="/tmp/tapeddef1$$"
# last direction of tape - 0 forward, 1 backward
dirflag=0

##########  LABEL CODE ##########
# get rid of any label -- not sure if this will work - needs testing

if [ $label = "y" ]
then dd $iflag of=/dev/null $ibsflag $rcbsflag $rchflag files=1 2> $ef1
     cmp -s - $ef1 <<EOF
0+0 records in
0+0 records out
EOF

    if [ $? -eq 0 ]
    then echo "tapedd: no label found on tape." 1>&2
    fi
			
    grep -s /dev/nrmt $ef1
    if [ $? -eq 0 ]
    then echo "tapedd: device error - label not advanced past" 1>&2
    fi
fi
##########  END OF LABEL CODE ###

# command loop starts here

trap 'rm $ofile $ef1 > /dev/null; exit' 2 1

echo "(at the prompt press ? and return for help)"


while true
do
	echo
	echo -n "tapedd> "
	read command param newval

	case $command in

		q | quit) 
		   rm $ofile $ef1 > /dev/null
		   echo So long!  Glad to be of service.
		   exit 0;;

		v | view)
		   echo current command parameters are:
		   echo
		   echo density $density
		   echo blocksize $blocksize characters
		   if [ "$forv" = "f" ]
		   then echo fixed length records
		        echo recordsize $recsize characters
		   else echo variable length records
		   fi
		   if [ "$aore" = "a" ]
		   then echo tape is ascii format
		   else echo tape is ebcdic format
		   fi

##########  LABEL CODE ##########
		   if [ "$label" = "n" ]
		   then echo no label
		   else echo labeled
		   fi
##########  END OF LABEL CODE ###

		   echo default base file name:  $fname;;

		r | read)
		   if [ "${param-""}" ]
		   then if [ "$param" -lt 1 ]
		   	then if [ "$param" = "-fast" ]
			     then fflag=1
				  if [ "${newval-""}" ]
				  then if [ $newval -lt 1 ]
				       then echo "Bad parameter.  \
At least one file must be read" 1>&2
				       continue
				       else nfiles=$newval
				       fi
				  else nfiles=1

				  fi
			     else echo "Bad parameter.  At least one file \
must be read" 1>&2
			     continue
			     fi
			else nfiles=$param
			     if [ "${newval-""}" = "-fast" ]
			     then fflag=1
			     else fflag=0
			     fi
			fi
		   else nfiles=1
			fflag=0
		   fi
		   cfiles=1

		   # advance past EOF gap
		   if [ $dirflag -eq 1 ]
		   then mt fsf
		   fi

		   while [ $cfiles -le $nfiles ]
		   do
			echo -n "reading..."
		   	dd $iflag $oflag $ibsflag $rcbsflag $rchflag \
files=1 2> $ef1
			echo done
			cmp -s - $ef1 <<EOF
0+0 records in
0+0 records out
EOF

			if [ $? -eq 0 ]
			then echo "read: nothing found on tape at current \
location - read aborted after `expr $cfiles - 1` file(s) read" 1>&2
			     dirflag=0
			     break
			fi
			
			grep -s /dev/nrmt $ef1
			if [ $? -eq 0 ]
			then echo "read: device error - read aborted \
after `expr $cfiles - 1` files read" 1>&2
			     break
			fi
			
			dirflag=0

			if [ $fflag -eq 0 ]
			then echo Figuring out type of file...
			     file $ofile
			     echo
			fi

       			while [ $fflag -eq 0 ]
			do 
				echo -n "Do you wish to view the file just \
read (y or n) [ y ] ? > "
				read yorn
				if [ "$yorn" = "y" -o -z "$yorn" ]
				then more $ofile
				     break
				elif [ "$yorn" = "n" ]
				then break
				else echo Please answer y or n! 1>&2
				fi
			done

       			while [ $fflag -eq 0 ]
			do 
				echo -n "Do you wish to save the file just \
read (y, n, q, f, or ? for help) [ y ] ? > "
				read yorn
				case "$yorn" in
					"" | y) svflag=1
						break;;
					n)	svflag=0
						echo "file not saved"
						break;;
					q)	echo "read aborted \
after `expr $cfiles` files read" 1>&2
						break 2;;
					f)	fflag=1
						echo switching to \
fast read mode
						break;;
					\?)	cat <<EOF
Typing 'y' will allow you to save the file just read under a filename of
your choice.

Typing 'n' will cause the file just read to not be saved.

Typing 'q' will abort the read.

Typing 'f' (for 'fast') will cause the read to continue, but no further
questions will be asked.  Files read will be named according to the
default filename.

Typing '?' will print this text.

EOF
;;

					*) echo Please type y, \
n, q, f, or ? 1>&2
;;

				esac

			done

			while [ $fflag -eq 0 -a $svflag -eq 1 ]
			do
				echo
				echo -n "What do you wish to name this file \
[ $fname$fcount ] ? > "
				read ufname
				if [ "$ufname" ]
				then mv $ofile $ufname 2>$ef1
				          if [ -s $ef1 ]
					     then echo "read: unable to \
rename file for the following reason" 1>&2
					     cat $ef1 1>&2
					     continue
				          fi
					  cfiles=`expr $cfiles + 1`
					  break
				else mv $ofile $fname$fcount 2>$ef1
				     if [ -s $ef1 ]
				     then echo "read: unable to rename file \
for the following reason" 1>&2
					  cat $ef1 1>&2
					  continue
				     fi
	
				     fcount=`expr $fcount + 1`
				    break
				fi
			done

		   	if [ $fflag -eq 1 ]
		   	then mv $ofile $fname$fcount 2>$ef1
		        	if [ -s $ef1 ]
				then echo "read: unable to rename file \
for the following reason" 1>&2
				     cat $ef1 1>&2
				     echo "read aborted after \
`expr $cfiles - 1` files read" 1>&2
				     break
				fi
	

			     echo file $fname$fcount created
			     fcount=`expr $fcount + 1`
			     cfiles=`expr $cfiles + 1`
			fi
		   done;;

		w | write) 
		   if [ -n "${param-""}" ]
		   then wfname=$param
		   else while true
		   	do
				echo "What is the name of the file(s) you \
wish written?"
				echo -n "filename> "
				read wfname
				if [ "${wfname-""}" = "" ]
				then echo "You must supply a file name!" 1>&2
				else break
				fi
		        done
		   fi


		   for i in $wfname
		   do

		   if [ ! -s $i ]
		   then echo "write:  File $i doesn't exist!  Not writing \
$i" 1>&2
			continue
		   elif [ ! -r $i ]
		   then echo "write:  File $i not readable!  Not writing \
$i" 1>&2
			continue
		   elif [ -d $i ]
		   then cat <<EOF 1>&2
write:  File is a directory.  Please use "write *" while connected to
$i to write it.  Not writing $i
EOF
			continue
		   fi

		   echo writing...
	  	   dd if=$i $woflag $obsflag $wcbsflag $wchflag 2> $ef1

		   # now do some error checking
		   cmp -s - $ef1 <<EOF
0+0 records in
0+0 records out
EOF

		   if [ $? -eq 0 ]
		   then echo "write:  unable to write from $wfname" 1>&2
			continue
		   else grep -s "records in" $ef1
			if [ $? -eq 1 ]
			then echo "write: unable to write for following \
reason" 1>&2
			     cat $ef1 1>&2
			     continue
			fi
		   fi

		grep -s /dev/nrmt $ef1
		if [ $? -eq 0 ]
		then echo "write: device error - write aborted" 1>&2
		     break
		fi
		echo done
		dirflag=0

		done;;

		S | [sS]tatus) 
		   echo checking status...
		   mt -f $ifile status 2> /dev/null
		   if [ $? -gt 0 -a $? -le 2 ]
		   then echo "Status check failed. check parameters and/or \
tape drive" 1>&2
		   fi;;

		R | [rR]ewind) 
		   echo -n rewinding tape...
		   mt -f $ifile rewind 2> /dev/null
		   if [ $? -gt 0 ]
		   then echo
			echo "Rewind failed. check parameters and/or \
tape drive" 1>&2
		   else echo done
		   fi
		   dirflag=0

##########  LABEL CODE ##########
		   # get rid of any label
		   if [ $label = "y" ]
		   then dd $iflag of=/dev/null $ibsflag \
$rcbsflag $rchflag files=1 2> $ef1
			cmp -s - $ef1 <<EOF
0+0 records in
0+0 records out
EOF

			if [ $? -eq 0 ]
			then echo "tapedd: no label found on tape." 1>&2
			fi
			
			grep -s /dev/nrmt $ef1
			if [ $? -eq 0 ]
			then echo "tapedd: device error - label \
not advanced past" 1>&2
			fi
		   fi
##########  END OF LABEL CODE ###

		   ;;

		B | [bB]ack | [bB]ack\-up) 
		   n=${param-""}
		   if [ -z "$n" -o "$n" -le 0 ]
		   then if [ -n "$n" -a "$n" -le 0 ]
			then echo "You must supply a numerical argument \
greater than zero!" 1>&2
			fi
			while true
			do 
				echo -n "How many files do you wish to go \
back past [ 1 ] ? > "
				read n
				if [ -z "$n" -o "$n" -gt 0 ]
				then if [ -z "$n" ]
				     then n=1
				     fi
				     break
				else echo "You must supply a numerical \
argument greater than zero!" 1>&2
				fi
			done
		   fi
		   echo -n backing up...
		   if [ $dirflag -eq 0 ]
		   then n=`expr $n + 1`
		   fi
		   mt -f $ifile bsf $n 2> /dev/null
		   if [ $? -gt 0 ]
		   then echo
			echo "operation failed; current tape position \
unknown " 1>&2
		        echo "check parameters and/or tape drive" 1>&2
		   else echo done
		   fi

		   # hack to check if at start of tape and to set
		   # dirflag to 0 if we are and 1 if not
		   mt -f $ifile status >$ef1
		   grep -s BOT $ef1
		   dirflag=$?

##########  LABEL CODE ##########
		   if [ $label = "y" -a $dirflag -eq 0 ]
		   then dd $iflag of=/dev/null $ibsflag \
$rcbsflag $rchflag files=1 2> $ef1
			cmp -s - $ef1 <<EOF
0+0 records in
0+0 records out
EOF

			if [ $? -eq 0 ]
			then echo "tapedd: no label found on tape." 1>&2
			fi
			
			grep -s /dev/nrmt $ef1
			if [ $? -eq 0 ]
			then echo "tapedd: device error - label \
not advanced past" 1>&2
			fi
		   fi
##########  END OF LABEL CODE ###

;;

   		F | [fF]orward) 
		   n=${param-""}
		   if [ -z "$n" -o "$n" -le 0 ]
		   then if [ -n "$n" -a "$n" -le 0 ]
			then echo "You must supply a numerical argument \
greater than zero!" 1>&2
			fi
			while true
			do 
				echo -n "How many files do you wish to go \
forward past [ 1 ] ? > "
				read n
				if [ -z "$n" -o "$n" -gt 0 ]
				then if [ -z "$n" ]
				     then n=1
				     fi
				     break
				else echo "You must supply a numerical \
argument greater than zero!" 1>&2
				fi
			done
		   fi
		   echo -n going forward...
		   n=`expr $n + $dirflag`
		   mt -f $ifile fsf ${n-1} 2> /dev/null
		   if [ $? -gt 0 ]
		   then echo
			echo "operation failed; current tape position \
unknown " 1>&2
		        echo "check parameters and/or tape drive" 1>&2
		   else echo done
		   fi
		   dirflag=0;;

		[h\?] | help) 
		   if [ -z "${param-""}" ]
		   then cat  <<EOF
Commands are invoked by their first letter as listed below (note that
case is significant), or by their full name.  Return must be pressed
after commands.  Commands are: 

Status (of tape drive)			read files
Rewind tape				write files
Forward tape				change (parameters)
Back-up tape				quit
help					view current command params

The following commands require their full names to be invoked, and work
as do their counterparts ls(1), cd(1), and pwd(1):

ls (list directory)			pwd (print working directory)
cd (change directory)

For more specific help, say help <command>
EOF
		   else case $param in
				S | [sS]tatus) cat <<EOF
The Status command invokes the status option of mt(1) on the tape drive
currently in use.
EOF
;;
				R | [rR]ewind) cat <<EOF
The Rewind command is used to rewind the tape currently mounted to its
beginning.  If the tape is labeled, it then advances past the label.
EOF
;;
				B | [bB]ack | [bB]ack\-up) cat <<EOF
The Back-up command is used to partially rewind the tape.  You may give
this command a number on the command line telling it how many files to
back up over (for example, Back-up 3 to the tapedd prompt would back up
over three files), or the command will prompt you for a number.  Note
that if you back up over the label, tapedd will not automatically
advance past it again.
EOF
;;
				F | [fF]orward) cat <<EOF
The Forward command is used to advance the tape past files.  You may
give this command a number on the command line telling it how many files
to advance past (for example, Forward 3 to the tapedd prompt would
advance past three files), or the command will prompt you for a number.
WARNING:  if you tell tapedd to advance n files, and there are less than
n files between the current position of the tape and the end of the
tape, tapedd will continue advancing the tape until it reaches the end
of the tape.  The possibility exists that you could unwind your whole
tape off of your reel.
EOF
;;
				v | view) cat <<EOF
The view command displays the currently set parameters.
EOF
;;
				q | quit) cat <<EOF
The quit command exits tapedd.
EOF
;;
				r | read) cat <<EOF
The read command reads files from the tape using the tape facility dd
and the parameters that you have chosen.  The number of files read is
determined by the numerical argument given to the command (as in the
Forward and Back-up commands), or 1 if no such argument is given.
     As each file is read, tapedd will first do a file(1) on it, then ask
you if you wish to view the file using more(1), and lastly will ask you
whether or not you wish to save the file.  You may obtain help on your
options there by responding '?' to that question.
     You may override the steps in the above paragraph if you give the
read command the argument '-fast'.  Saying 'read -fast' will read the
number of files in the files variable, placing them under the
appropriate default filenames.  You may also combine the -fast and number
of files read command line options on one line, i.e. 'read 3 -fast' will
read 3 files and place them in default file names.
EOF
;;
				w | write) cat <<EOF
The write command prompts you for a file name, and then writes that file
onto the tape using the currently set parameters.  You may specify the
file to be written on the command line.  You may use wildcard characters
when specifying the filename, but directories may not be written.
Connect to the directory and use "write *" to write the directory.
EOF
;;
				h | help) cat <<EOF
The help command gives help about tapedd.  In addition to the usual h or
help, it may be invoked by saying ?.
EOF
;;
				c | change) cat <<EOF 
The change command allows you to change the parameters used to read the
tape.  By simply saying c or change, you are prompted for the parameter
to be changed and the new value.  You may also include one or both of
the param and new value on the command line.  For example, saying
'change density' will cause tapedd to prompt you for the new value of
density.  Saying 'change density 6250' will change the density with no
further prompting.  The same thing applies at the parameter prompt.  By
saying 'change' you will get the list of possible params, and then
saying 'density 6250' would change the density immediately, bypassing
the new value prompt.
EOF
;;

				ls) cat <<EOF
The ls command has the same effect as the ls(1) command.  For those
users who use the C shell, note that the ~user syntax for referencing a
user's home directory does not work, as tapedd is written in the Bourne
shell.
EOF
;;

				cd) cat <<EOF
The cd command connects to the directory given as an argument, or to
your home directory if no argument is given.  See cd(1) for more
details.
EOF
;;

				pwd) cat <<EOF
The pwd command prints the current directory that you are connected to.
See pwd(1) for more details.
EOF
;;

				*) echo "help:  unknown option $param" 1>&2
			esac
		   fi
			;;

		c | change)
		   if [ -z "${param-""}" ]
		   then cat <<EOF
Which parameter would you like to change? (refer to parameter by its
name or you may use the abbreviation in brackets.)
density [den]			length (fixed or variable length records)
recordsize [rec]		format (ascii or ebcdic format)
blocksize [block]		label 
filename (default) [dfname]
EOF
			echo -n "param> "
			read param newval
			if [ -z "$param" ]
			then echo "no param given, nothing to change" 1>&2
			     continue
			fi
		   fi

		   if [ -z "${newval-""}" ]
		   then echo -n "new value for $param> "
			read newval
			if [ -z "$newval" ]
			then echo "no new value given, nothing changed" 1>&2
			     continue
			fi
		   fi

		   case $param in

			den | density)
			     if [ $newval -ne 1600 -a $newval -ne 6250 ]
			     then echo "Bad density, must be either 1600 \
or 6250.  Nothing changed." 1>&2
			     else density=$newval
			     	  ifile="/dev/nrmt$density"
			     	  iflag="if=$ifile"
				  woflag="of=$ifile"
				  echo "density changed to $density"
			     fi;;

			rec | recordsize)
			     if [ $newval -lt 1 ]
			     then echo "must be at least one character \
per record.  Nothing changed." 1>&2
			     else recsize=$newval
				  if [ $forv = "f" ]
				  then rcbsflag="conv=unblock cbs=$recsize"
				       wcbsflag="conv=block cbs=$recsize"
				  fi
				  echo "record size changed to $recsize"
			     fi;;

			block | blocksize)
			       if [ $newval -lt 1 ]
			       then echo "must be at least one character \
per block.  Nothing changed." 1>&2
			       else blocksize=$newval
				    ibsflag="ibs=$blocksize"
				    obsflag="obs=$blocksize"
				    echo "blocksize changed to $blocksize"
			       fi;;

			length) if [ $newval != "f" -a $newval != "v" ]
			      	then echo "value must be f or v.  Nothing \
changed." 1>&2
			      	else forv=$newval
				     if [ $forv = "f" ]
				     then rcbsflag="conv=unblock cbs=$recsize"
					  wcbsflag="conv=block cbs=$recsize"
				     else cbsflag=""
					  wcbsflag=""
				     fi
				     if [ $forv = "v" ]
				     then echo "format changed to variable \
length records."
				     else echo "format changed to fixed \
length records."
				     fi
			      fi;;

			format) if [ $newval != "a" -a $newval != "e" ]
			        then echo "value must be a or e.  Nothing \
changed." 1>&2
			      	else aore=$newval
				     if [ $aore = "a" ]
				     then rchflag=""
					  wchflag=""
				     else rchflag="conv=ascii"
					  wchflag="conv=ebcdic"
				     fi
				     if [ $aore = "a" ]
				     then echo "tape format changed to ascii"
				     else echo "tape format changed to ebcdic"
				     fi
			      fi;;

##########  LABEL CODE ##########
			label) if [ $newval != "y" -a $newval != "n" ]
			       then echo "value must be y or n.  Nothing \
changed." 1>&2
			       else label=$newval
				    if [ $label = "y" ]
				    then echo "tape is now considered labeled"
				    else echo "tape is now considered \
unlabeled"
				    fi
			     fi;;
##########  END OF LABEL CODE ###

			dfname | filename)
				fname=$newval
				echo "new default file name is $fname";;

			*) echo "change: unknown parameter $param" 1>&2;;
		   esac;;

		ls) if [ "${param-""}" ]
		    then if [ "${newval-""}" ]
			 then ls $param $newval
			 else ls $param
			 fi
		    else ls
		    fi;;

		cd) if [ "${param-""}" ]
		    then if [ -d "$param" -a -r "$param" ]
			 then cd $param
			 else echo "cd:  cannot connect to $param" 1>&2
			 fi
		    else cd
		    fi
		    echo -n "now connected to "
		    pwd;;

		pwd) echo -n "connected to "
		     pwd;;

		"") ;;

		*) echo "tapedd: unknown command $command" 1>&2;;
	esac
done
