#/bin/bash

source paramrouts

echo "Warning: This program cannot detect if the disk in drive $mnr"
echo "         contains the right part."

if ! question "Salvage data"; then
 exit
fi

if [ $descrdown = y ]; then
 offset=`expr $doffset + 3`
else
 offset=`expr $doffset + 4`
fi
offset=`expr $offset \* 512`

echo 
echo Salvaging all readable data. This may take a while.
echo
echo "Press \`a' to abort operation."
echo

touch map
tail -f map &
mappid=$!

#echo watch... message?
watch=y

if [ $eccmethod = none ]; then

 if ! salvage $mdev -b$offset -c$psize >$1 2>/dev/null;
 then
  echo
  kill $mappid
  echo "Operation aborted."
  rm -f $1
  exit
 fi

 kill $mappid

else
 
 if ! salvage $mdev -b$offset -c$psize >$1 2>map;
 then
  echo
  kill $mappid
  echo "Operation aborted."
  rm -f $1
  exit
 fi

 if ! salvage $mdev -b$[$offset+psize] -c$[$eccsizek * 1024] >$1.ecor 2>>map;
 then
  echo
  kill $mappid
  echo "Operation aborted."
  rm -f $1
  exit
 fi

 kill $mappid
 echo
 echo "Trying to correct read errors...."
 echo 

#We use the -v flag to make the output more interesting :)
 if ! ecor -v -r $eccargs -a$availk $1 $1.ecor map >stillbad
 then
  echo
  echo "Internal error, operation aborted."
  rm -f $1
  exit
 fi

 echo
 echo "Error correction done."
 if [ `cat stillbad` = 0 ]; then
   echo "All unreadable data could be reconstructed."
   watch=n
 else
   echo "There were too many read errors for a complete repair,"
   echo `cat stillbad` " 1024-byte blocks of data could not be reconstruced."
 fi
 echo
 rm $1.ecor map stillbad

fi

echo
echo "Feeding the salvaged data to the archiver......"
if [ $watch = y ]; then
 echo "Watch the restore log for archiver errors."
fi
echo 
echo "If the salvaged disk was the last disk in the backup set, type o and e!"
echo "to end the $ttytitle."
echo
