#! /bin/sh
#
# Copyright by  The HDF Group and
#               The Board of Trustees of the University of Illinois.
# All rights reserved.
#
# This file is part of H4H5TOOLS. The full H4H5TOOLS copyright notice,
# including terms governing use, modification, and redistribution, is
# contained in the files COPYING and Copyright.html.  COPYING can be found
# at the root of the source code distribution tree; Copyright.html can be
# found at the root level of an installed copy of the electronic H4H5TOOLS
# document set, is linked from the top-level documents page, and can be
# found at http://www.hdfgroup.org/h4toh5/Copyright.html.  If you do not
# have access to either file, you may request a copy from help@hdfgroup.org.
#

srcdir=@srcdir@

H5TOH4=h5toh4               # a relative name
H5TOH4_BIN=`pwd`/$H5TOH4    # an absolute command path
export LD_LIBRARY_PATH=@LD_LIBRARY_PATH@

cmp='cmp -s'
diff='diff -c'
CP='cp'
DIRNAME='dirname'
LS='ls'
AWK='awk'

RM='rm -f'
SED='sed '

#H4DIFF=`echo $CC | sed -e 's/h4cc/:/' | cut -d: -f1`/'hdiff'
H4DIFF=`which \`echo $CC | cut -d' ' -f1\` | sed -e 's/h4cc/:/' | cut -d: -f1`/'hdiff'

# Verify if $H4DUMP is a valid command.
tmpfile=/tmp/testh5toh4.$$
$H4DIFF > $tmpfile
if test -s "$tmpfile"; then
  :
else
    echo "    Could not run the '$H4DIFF' command. The test can still proceed"
    echo "    but it may fail if '$H4DIFF' is needed to verify the output."
    echo "    You can make sure '$H4DIFF' is among your shell PATH and run"
    echo "    the test again. You may also visit http://www.hdfgroup.org"
    echo "    or email hdfhelp@hdfgroup.org for more information."
    H4DIFF=:
    H4DIFFVER=0
fi
$RM $tmpfile

# The build (current) directory might be different than the source directory.
if test -z "$srcdir"; then
   srcdir=.
fi
mkdir ../testfiles >/dev/null 2>&1

SRCDIR="$srcdir/../testfiles"
TESTDIR="../testfiles"
OUTDIR="../testfiles/Results"

test -d $OUTDIR || mkdir $OUTDIR

nerrors=0
verbose=yes

######################################################################
# test files
# --------------------------------------------------------------------
# All the test files copy from source directory to test directory
# NOTE: Keep this framework to add/remove test files.
#       Any test files from other tools can be used in this framework.
#       This list are also used for checking exist.
#       Comment '#' without space can be used.
# --------------------------------------------------------------------
LIST_HDF5_TEST_FILES="
$SRCDIR/tall.h5
$SRCDIR/tattr.h5
$SRCDIR/tcompound2.h5
$SRCDIR/tcompound.h5
$SRCDIR/tcompound-str.h5
$SRCDIR/tdset2.h5
$SRCDIR/tdset.h5
$SRCDIR/tgroup.h5
$SRCDIR/thlink.h5
$SRCDIR/timage.h5
$SRCDIR/tloop.h5
$SRCDIR/tmany.h5
$SRCDIR/tsds_attr.h5
$SRCDIR/tsds_dim.h5
$SRCDIR/tslink.h5
$SRCDIR/tstr2.h5
$SRCDIR/tstr.h5
$SRCDIR/ttable.h5
"

#
# copy test files and expected output files from source dirs to test dir
#
COPY_TESTFILES="$LIST_HDF5_TEST_FILES"

COPY_TESTFILES_TO_TESTDIR()
{
    # copy test files. Used -f to make sure get a new copy
    for tstfile in $COPY_TESTFILES
    do
        # ignore '#' comment
        echo $tstfile | tr -d ' ' | grep '^#' > /dev/null
        RET=$?
        if [ $RET -eq 1 ]; then
            # skip cp if srcdir is same as destdir
            # this occurs when build/test performed in source dir and
            # make cp fail
            SDIR=`$DIRNAME $tstfile`
            INODE_SDIR=`$LS -i -d $SDIR | $AWK -F' ' '{print $1}'`
            INODE_DDIR=`$LS -i -d $TESTDIR | $AWK -F' ' '{print $1}'`
            if [ "$INODE_SDIR" != "$INODE_DDIR" ]; then
                $CP -f $tstfile $TESTDIR
                if [ $? -ne 0 ]; then
                    echo "Error: FAILED to copy $tstfile ."

                    # Comment out this to CREATE expected file
                    exit $EXIT_FAILURE
                fi
            fi
        fi
    done
}

CLEAN_TESTFILES_AND_TESTDIR()
{
    # skip rm if srcdir is same as destdir
    # this occurs when build/test performed in source dir and
    # make cp fail
    SDIR=$SRCDIR
    INODE_SDIR=`$LS -i -d $SDIR | $AWK -F' ' '{print $1}'`
    INODE_DDIR=`$LS -i -d $TESTDIR | $AWK -F' ' '{print $1}'`
    if [ "$INODE_SDIR" != "$INODE_DDIR" ]; then
        $RM -r $TESTDIR
    fi
}

# Print a line-line message left justified in a field of 70 characters
# beginning with the word "Testing".
TESTING() {
    SPACES="                                                               "
    echo "Testing $* $SPACES" |cut -c1-70 |tr -d '\012'
}

# Run a test and print PASS or *FAIL*.  If a test fails then increment
# the `nerrors' global variable and (if $verbose is set) display the
# difference between the actual and the expected hdf4 files. The
# expected hdf4 files are in testfiles/Expected directory.
# The actual hdf4 file is not removed if $H4H5_NOCLEANUP is to a non-null
# value.
CONVERT() {
    # Run h5toh4 convert.
    TESTING $H5TOH4 $@

    #
    # Set up arguments to run the conversion test.
    # The converter assumes all hdf5 files has the .h5 suffix as in the form
    # of foo.h5.  It creates the corresponding hdf4 files with the .hdf suffix
    # as in the form of foo.hdf.  One exception is that if exactly two file
    # names are given, it treats the first argument as an hdf5 file and creates
    # the corresponding hdf4 file with the name as the second argument, WITOUT
    # any consideration of the suffix.  (For this test script, in order to
    # match the output hdf4 file with the expected hdf4 file, it expects the
    # second file of the two-files tests has the .hdf suffix too.)
    #
    # If SRCDIR != OUTDIR, need to copy the input hdf5 files from the SRCDIR
    # to the OUTDIR and transform the input file pathname because of the suffix
    # convention mentioned above.  This way, the hdf4 files are always created
    # in the OUTDIR directory.
    #

    INFILES=""
    OUTFILES=""
    MULTIRUN=""
    ROOT=""

    case "$1" in
    "-m")		# multiple files conversion
	MULTIRUN="-m"
	shift
	for f in $*
	do
	    if test "$SRCDIR" != "$OUTDIR"; then
		cp $SRCDIR/$f $OUTDIR/$f
	    fi
	    INFILES="$INFILES $f"
	    OUTFILES="$OUTFILES `basename $f .h5`$ROOT.hdf"
	    shift
	done
	;;
    * )			# Single file conversion
	case $# in
	1)  if test "$SRCDIR" != "$OUTDIR"; then
		cp $SRCDIR/$1 $OUTDIR/$1
	    fi
	    INFILES="$1"
	    OUTFILES="`basename $1 .h5`$ROOT.hdf"
	    ;;
	2) 		# hdf4 file specified
	    if test "$2" = "-r"; then
		ROOT="-r";
	        if test "$SRCDIR" != "$OUTDIR"; then
		    cp $SRCDIR/$1 $OUTDIR/$1
	        fi
	        INFILES="$1"
	        OUTFILES="`basename $1 .h5`$ROOT.hdf"
            else
	       if test "$SRCDIR" != "$OUTDIR"; then
		  cp $SRCDIR/$1 $OUTDIR/$1
	       fi
	       INFILES="$1"
	       OUTFILES="$2"
            fi
	    ;;
	3) #'-r' specified?
	    if test "$2" != "-r"; then
	        echo "Illegal arguments"
	        exit 1
            fi
	    if test "$SRCDIR" != "$OUTDIR"; then
		cp $SRCDIR/$1 $OUTDIR/$1
	    fi
	    INFILES="$1"
	    OUTFILES="`basename $3 .hdf`$ROOT.hdf"
	    ROOT="-r"
	    ;;
	*)		# Illegal
	    echo "Illegal arguments"
	    exit 1
	    ;;
	esac
	;;
    esac

    # run the conversion and remove input files that have been copied over
    if test -n "$ROOT"; then
    (
	cd $OUTDIR
	$H5TOH4_BIN $MULTIRUN $INFILES $ROOT $OUTFILES 2>/dev/null
	if test "$SRCDIR" != "$OUTDIR"; then
	    $RM $INFILES
	fi
    )
    else
    (
	cd $OUTDIR
	$H5TOH4_BIN $MULTIRUN $INFILES 2>/dev/null
	if test "$SRCDIR" != "$OUTDIR"; then
	    $RM $INFILES
	fi
    )
    fi

    # Verify results
    for f in $OUTFILES
    do
	if $cmp $SRCDIR/Expected/$f $OUTDIR/$f
	then
	    :
            echo " PASSED"
	else
	    # Use hdiff to compare the HDF4 files.
	    outfile=`basename $f .hdf`
	    expect_out=$outfile.expect
	    actual_out=$outfile.actual
            $H4DIFF $SRCDIR/Expected/$outfile.hdf $OUTDIR/$outfile.hdf 
                 RET=$?
                 if [ $RET != 0 ] ; then
                  echo "*FAILED*"
                  nerrors="`expr $nerrors + 1`"
                 else
                  echo " PASSED"
                 fi
         fi

	# Clean up output file
	if test -z "$H4H5_NOCLEANUP"; then
	    $RM $expect_out $actual_out
	    $RM $OUTDIR/$f
	fi
    done
#    if test "passed" = "$result"; then
#	    echo " PASSED"
#    fi
}



##############################################################################
##############################################################################
###			  T H E   T E S T S                                ###
##############################################################################
##############################################################################

$RM $OUTDIR/*.hdf $OUTDIR/*.tmp
COPY_TESTFILES_TO_TESTDIR
#
# The HDF4 filenames are created based upon the HDF5 filenames
# without the extension.
#

# test for converting H5 groups to H4 Vgroups.
CONVERT tgroup.h5

# test for converting H5 datasets to H4 SDS's.
CONVERT tdset.h5

# test for converting H5 attributes to H4 attributes.
CONVERT tattr.h5

# test for converting H5 soft links.
CONVERT tslink.h5

# test for converting H5 hard links.
CONVERT thlink.h5

# test for converting H5 compound data type to H4 Vdata.
CONVERT tcompound.h5

# test for converting H5 compound data type to H4 Vdata. One member datatype is an HDF5 fixed-size string
CONVERT tcompound-str.h5

# test for converting all H5 objects at in same file.
CONVERT tall.h5

# tests for converting H5 objects with loops.
CONVERT tloop.h5

# test for converting extendable H5 datasets to H4 SDS's.
CONVERT tdset2.h5

# test for converting extendable H5 datasets with compound data type to H4 Vdata.
CONVERT tcompound2.h5


# tests for converting H5 objects from many different pathways.
CONVERT tmany.h5

# tests for converting H5 string objects.
CONVERT tstr.h5

# tests for converting more H5 string objects.
CONVERT tstr2.h5
CONVERT timage.h5
CONVERT ttable.h5
CONVERT tsds_attr.h5
CONVERT tsds_dim.h5

#
# The test for conversion are the same as above with the only difference
# being that the HDF4 filenames are given explicitly.
#

$RM $OUTDIR/*.tmp
CONVERT tgroup.h5 tgroup.hdf
CONVERT tdset.h5 tdset.hdf
CONVERT tattr.h5 tattr.hdf
CONVERT tslink.h5 tslink.hdf
CONVERT thlink.h5 thlink.hdf
CONVERT tcompound.h5 tcompound.hdf
CONVERT tcompound-str.h5 tcompound-str.hdf
CONVERT tall.h5 tall.hdf
CONVERT tloop.h5 tloop.hdf
CONVERT tdset2.h5 tdset2.hdf
CONVERT tcompound2.h5 tcompound2.hdf
CONVERT tmany.h5 tmany.hdf
CONVERT tstr.h5 tstr.hdf
CONVERT tstr2.h5 tstr2.hdf
CONVERT timage.h5 timage.hdf
CONVERT ttable.h5 ttable.hdf
CONVERT tsds_attr.h5 tsds_attr.hdf
CONVERT tsds_dim.h5 tsds_dim.hdf

#
# Again, the test for conversion are the same as the first set of test.
# Here, multiple conversion are done on HDF5 files at one time.
#

$RM $OUTDIR/*.hdf $OUTDIR/*.tmp
CONVERT -m tgroup.h5 tdset.h5 tattr.h5 tslink.h5 thlink.h5
CONVERT -m tcompound.h5 tcompound-str.h5 tall.h5
CONVERT -m tloop.h5
CONVERT -m tdset2.h5 tcompound2.h5 tmany.h5
CONVERT -m tstr.h5 tstr2.h5

$RM $OUTDIR/*.hdf $OUTDIR/*.tmp
CONVERT tgroup.h5 -r 
CONVERT tdset.h5 -r
CONVERT tattr.h5 -r
CONVERT tslink.h5 -r
CONVERT thlink.h5 -r
CONVERT tcompound.h5 -r
CONVERT tcompound-str.h5 -r
CONVERT tall.h5 -r
CONVERT tloop.h5 -r
CONVERT tdset2.h5 -r
CONVERT tcompound2.h5 -r
CONVERT tmany.h5 -r
CONVERT tstr.h5 -r
CONVERT tstr2.h5 -r
CONVERT timage.h5 -r
CONVERT ttable.h5 -r
CONVERT tsds_attr.h5 -r
CONVERT tsds_dim.h5 -r


$RM $OUTDIR/*.hdf $OUTDIR/*.tmp
CONVERT tgroup.h5 -r tgroup-r.hdf
CONVERT tdset.h5 -r tdset-r.hdf
CONVERT tattr.h5 -r tattr-r.hdf
CONVERT tslink.h5 -r tslink-r.hdf
CONVERT thlink.h5 -r thlink-r.hdf
CONVERT tcompound.h5 -r tcompound-r.hdf
CONVERT tcompound-str.h5 -r tcompound-str-r.hdf
CONVERT tall.h5 -r tall-r.hdf
CONVERT tloop.h5 -r tloop-r.hdf
CONVERT tdset2.h5 -r tdset2-r.hdf
CONVERT tcompound2.h5 -r tcompound2-r.hdf
CONVERT tmany.h5 -r tmany-r.hdf
CONVERT tstr.h5 -r tstr-r.hdf
CONVERT tstr2.h5 -r tstr2-r.hdf
CONVERT timage.h5 -r timage-r.hdf
CONVERT ttable.h5 -r ttable-r.hdf
CONVERT tsds_attr.h5 -r tsds_attr-r.hdf
CONVERT tsds_dim.h5 -r tsds_dim-r.hdf

# to do: -m and -r toghether

if test $nerrors -eq 0 ; then
	echo "All h5toh4 tests passed."
fi

if test -z "$H4H5_NOCLEANUP"; then
    $RM -r $OUTDIR
    # Clean up temporary files/directories
    CLEAN_TESTFILES_AND_TESTDIR
fi
exit $nerrors
