#!/bin/sh

execdir="$PWD"

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="A file is found when the set records its name in a code page"
dashes=`echo "$banner" | sed s/./-/g`

echo $dashes
echo $banner
echo $dashes

# The set was written by a machine using a code page, so it records the name
# in Windows-1252 while the file on disk is named in UTF-8.
tar -xzf "$TESTDATA/codepage-name.tar.gz" 2>&1 || { echo "ERROR: Could not extract the test files" ; exit 1; } >&2

name=`printf 'data_\303\250.bin'`
cp "$name" original.bin

$PARBINARY v -q recovery.par2 || { echo "ERROR: The file was not found under its UTF-8 name" ; exit 1; } >&2

# The repair has to write to the file which is there, not to the name the set
# records.
printf 'XXXXXXXXXXXXXXXX' | dd of="$name" bs=1 seek=2048 conv=notrunc 2>/dev/null

$PARBINARY r -q recovery.par2 || { echo "ERROR: Repair failed" ; exit 1; } >&2

cmp "$name" original.bin || { echo "ERROR: The repaired file does not match the original" ; exit 1; } >&2

# A file which is missing is written under its name in UTF-8.
rm -f "$name"

$PARBINARY r -q recovery.par2 || { echo "ERROR: Repair of the missing file failed" ; exit 1; } >&2

cmp "$name" original.bin || { echo "ERROR: The missing file was not written under its UTF-8 name" ; exit 1; } >&2

# A file under the name in Windows-1252 has the wrong name, and a repair
# renames it to its name in UTF-8. Only a file system which takes any bytes
# in a name can hold it.
codepage=`printf 'data_\350.bin'`
if mv "$name" "$codepage" 2>/dev/null && [ ! -f "$name" ]
then
  $PARBINARY v -q recovery.par2 > /dev/null 2>&1
  result=$?
  if [ $result -ne 1 ]
  then
    echo "ERROR: Verifying the file under its Windows-1252 name gave $result, expected 1" >&2
    exit 1
  fi

  $PARBINARY r -q recovery.par2 || { echo "ERROR: Repair of the file under its Windows-1252 name failed" ; exit 1; } >&2

  cmp "$name" original.bin || { echo "ERROR: The file was not renamed to its UTF-8 name" ; exit 1; } >&2
fi

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

exit 0
