#!/bin/sh

execdir="$PWD"

# valgrind tests memory usage.
# wine allow for windows testing on linux
if [ -n "${PARVALGRINDOPTS+set}" ]
then
    PARBINARY="valgrind $PARVALGRINDOPTS $execdir/par2"
elif [ "`which wine`" != "" ] && [ -f "$execdir/par2.exe" ]
then
    PARBINARY="wine $execdir/par2.exe"
else
    PARBINARY="$execdir/par2"
fi


if [ -z "$srcdir" ] || [ "." = "$srcdir" ]; then
  srcdir="$PWD"
  TESTDATA="$srcdir/tests"
else
  srcdir="$PWD/$srcdir"
  TESTDATA="$srcdir/tests"
fi

TESTROOT="$PWD"

testname=$(basename $0)
rm -f "$testname.log"
rm -rf "run$testname"

mkdir "run$testname" && cd "run$testname" || { echo "ERROR: Could not change to test directory" ; exit 1; } >&2

banner="Creating 1024 byte test data file"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

dd if=/dev/urandom of=datafile bs=1024 count=1 || { echo "ERROR: Unable to create test data file" ; exit 1; } >&2
ls -l

banner="Creating PAR 2.0 recovery data (block size 200)"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

$PARBINARY c -s200 -c1 recovery datafile || { echo "ERROR: Creating PAR 2.0 data failed" ; exit 1; } >&2
ls -l

banner="Damaging data file (trim first 100 bytes)"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

mv datafile datafile.orig
dd if=datafile.orig of=datafile bs=100 skip=1 || { echo "ERROR: Unable to create damaged data file" ; exit 1; } >&2
rm datafile.orig
ls -l

banner="Repairing using PAR 2.0 data (with skip leaway 99 - should fail)"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

$PARBINARY r -N -S99 -vv recovery.par2 && { echo "ERROR: Repair should not be possible with skip leaway set to 99" ; exit 1; } >&2
ls -l

banner="Repairing using PAR 2.0 data (with skip leaway 100 - should succeed)"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

$PARBINARY r -N -S100 -vv recovery.par2 || { echo "ERROR: Repair should be possible with skip leaway set to 100" ; exit 1; } >&2
ls -l

cd "$TESTROOT"
rm -rf "run$testname"

exit 0
