#!/bin/bash
init()
{
	BLKSIZ=1024
	if [ -f $1 ] ; then
		if ask "overwrite $1" ; then
			echo $1 removed
		else
			exit
		fi
	fi
	FILE=$1
	SYS=`uname`
	#########################################################
	# Speciy MOUNT UMOUNT and DRV for each system here .... #
	if [ $SYS"X" = "LinuxX" ] ; then
		MOUNT="mount /dev/fd0"
		UMOUNT="umount /dev/fd0"
		DRV=/mnt/floppy
	elif [ $SYS"X" = "CYGWIN_NT-4.0X" -o $SYS"X" = "CYGWIN_NT-5.0X" ] ; then
		MOUNT="echo Checking ..."
		UMOUNT="echo"
		DRV=a:
	elif [ $SYS"X" = "FreeBSDX" ] ; then
		MOUNT="mount -t msdos /dev/fd0 /fd0"
		UMOUNT="umount /fd0"
		DRV=/fd0
	else
		echo "Unknown System"
		exit 1
	fi
	#########################################################
}

# ----------------------------------------------------------------------------

ask()
{
	while true ; do
		echo -e $*"? \c"
		read REPLY
		if [ $REPLY"x" = "yx" -o $REPLY"x" = "Yx" ] ; then
			return 0
		elif [ $REPLY"x" = "nx" -o $REPLY"x" = "Nx" ] ; then
			return 1
		fi
	done
}

# ----------------------------------------------------------------------------

chkstat()
{
	if [ $1 -eq 0 ] ; then
		return
	fi
	echo Exiting due to previous error ...
	exit $1
}

# ----------------------------------------------------------------------------

next_disk()
{
	echo -e "Insert disk $DISK in $DRV and Press Enter ... \c"
	read NOTHING
	$MOUNT
	if [ $? -ne 0 ] ; then
		return 1
	fi
	LS=`ls -l $DRV/FDCUT.$DISK | awk '{gsub(/\*/,"");sub(/..[0-9]$/,"");print}'`
	if [ $? -ne 0 ] ; then
		return 1
	fi
	if [ $DISK -eq "001" ] ; then
		TS1=`echo $LS | awk 'BEGIN{ OFS=":"; }{print $6,$7,$8,$9}'`
	else
		TS=`echo $LS | awk 'BEGIN{ OFS=":"; }{print $6,$7,$8,$9}'`
		if [ "$TS" != "$TS1" ] ; then
			ls -l $DRV
			echo This does not appear to be in the same backup set
			ask "do you want to continue" 
		fi
	fi
	if [ $? -ne 0 ] ; then
		return 1
	fi
	echo blocks extracted so far: $DONE
	SIZE=`echo $LS | awk '{if ($5 + 0) print $5; else exit(1) }'`
	if [ $? -ne 0 ] ; then
		return 1
	fi
	BLOCKS=`echo $SIZE $BLKSIZ | awk '{print int(($1+($2 - 1))/$2)}'`
	dd if=$DRV/FDCUT.$DISK of=$FILE bs=$BLKSIZ seek=$DONE count=$BLOCKS
	return $?
}

# ----------------------------------------------------------------------------

# ... Start here

if [ $1"x" = "x" ] ; then
	echo usage: $0 filename
	exit
fi
init $1
chkstat $?
DISK=001
DONE=0
FINISH=0
while [ $FINISH -eq 0 ] ; do
	next_disk
	if [ $? -ne 0 ] ; then
		if ask "Problem with this disk --- Abort" ; then
			exit 1
		fi
	else
		DISK=`echo $DISK | awk '{ printf( "%03d\n", $1 + 1) }'`
		DONE=`echo $DONE $BLOCKS | awk '{print $1 + $2}'`
		if [ -f $DRV/FDCUT.ZZZ ] ; then
			FINISH=1
		fi
	fi
	$UMOUNT
done
