#!/bin/bash
#
# Usage: rasmerge
#
#    Merge a large file that's previously been split across several floppies
#    by rassplit back into the original file, putting it in the current
#    directory.
#

# The mount-point for the floppy drive
FLOPPY=/floppy

# The command used to mount the floppy
MOUNT="mount $FLOPPY"

# The unmount command
UMOUNT="umount $FLOPPY"

############################################################################

function remmd5 ()
{
   # usage : remmd5 <source> <dest>
   # 
   # treat the first line of <source> as an MD5 sum of the rest, if the
   # checksum is correct then copy the rest to <dest>.

   (
     read CORRECT_SUM
     SUM=`tee $2 | md5sum | sed 's/ .*//'`

     if [ "$SUM" != "$CORRECT_SUM" ]
     then
	echo "CHECKSUM FAILED !"
	rm -f $2
     else
	echo "Checksum passed"
     fi

   ) <$1
}

############################################################################

# Copy an md5sum-prefixed file from a floppy to a specified directory,
# removing and checking the md5 sum. Don't copy the file if the checksum
# fails.
function read_floppy ()
{
   DEST=$1

   echo "Put a floppy in the drive and press RETURN"
   printf '\a'
   read -e

   $MOUNT
   ( cd $FLOPPY
     for file in *
     do
        echo "Getting file $file ..."
        remmd5 $file $DEST/$file
     done
   )  
   $UMOUNT
}

############################################################################   

TMP="/tmp/rassplit.$$";
rm -rf $TMP
mkdir $TMP

echo "How many segments are there ?"
read SEGCOUNT

# Get segfiles and sumfiles from floppies until there are enough to
# regenerate all the segfiles.
read_floppy $TMP
until [ $SEGCOUNT == 1 -a -r "$TMP/xaa" ]                   || \
      ( cd $TMP ; [ $SEGCOUNT != 1 ] && ras -n$SEGCOUNT sum* )
do
   read_floppy $TMP
done
echo "All segfiles now present"

echo "Removing sumfiles ..."
rm -f $TMP/sum*

# Combine the segfiles and extract our original file and its checksum.
# Remove each file as soon as we've finished with it to save disk space.
echo "Merging segfiles ..."
(for i in $TMP/x??; do cat $i ; rm $i; done) | tar xvf -
rm -rf $TMP

echo "File rebuilt, testing checksum ..."
md5sum -v -c ras.md5sum
rm ras.md5sum


