#!/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

for f in test-1.data test-2.data
do
    dd if=/dev/urandom of=$f bs=1024 count=200 2>/dev/null \
        || { echo "ERROR: Could not create test data" ; exit 1; } >&2
done
cp test-1.data test-1.data.orig
cp test-2.data test-2.data.orig

$PARBINARY c -b40 -c40 testdata.par2 test-1.data test-2.data \
    || { echo "ERROR: creating repair files using PAR 2.0 failed" ; exit 1; } >&2


banner="purge keeps a complete file found under another file's name"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

mv test-1.data newname
mv test-2.data test-1.data

$PARBINARY r -p testdata.par2 newname > swapped.out 2>&1 \
    || { cat swapped.out ; echo "ERROR: repair using PAR 2.0 failed" ; exit 1; } >&2
cat swapped.out

cmp test-1.data test-1.data.orig \
    || { echo "ERROR: test-1.data does not match the original" ; exit 1; } >&2
cmp test-2.data test-2.data.orig \
    || { echo "ERROR: test-2.data was purged" ; exit 1; } >&2


banner="purge removes a damaged file found under another file's name"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

$PARBINARY c -b40 -c40 testdata.par2 test-1.data test-2.data \
    || { echo "ERROR: creating repair files using PAR 2.0 failed" ; exit 1; } >&2

mv test-1.data newname
mv test-2.data test-1.data
printf '\336\255\276\357' | dd of=test-1.data bs=1 seek=100000 count=4 conv=notrunc 2>/dev/null

$PARBINARY r -p testdata.par2 newname > damaged.out 2>&1 \
    || { cat damaged.out ; echo "ERROR: repair using PAR 2.0 failed" ; exit 1; } >&2
cat damaged.out

cmp test-1.data test-1.data.orig \
    || { echo "ERROR: test-1.data does not match the original" ; exit 1; } >&2
cmp test-2.data test-2.data.orig \
    || { echo "ERROR: test-2.data does not match the original" ; exit 1; } >&2
[ ! -e test-1.data.1 ] || { echo "ERROR: the damaged copy was not purged" ; exit 1; } >&2

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

exit 0
