#!/bin/bash
#
# Test lasrc.

base_scene="LC08_L1TP_040036_20141219_20160822_01_T1"
aux_file="L8ANC2014353.hdf_fused"

if [ "$#" -ne 1 ]; then
    echo "Usage:  $0 <path_to_lasrc>"
    exit 1
fi
bin_dir=$1

data_files=(${ESPA_UNIT_TEST_DATA_DIR}/espa-surface-reflectance/lasrc_ref_toa/*)
input_dir=$ESPA_UNIT_TEST_DATA_DIR/espa-surface-reflectance/input_l8

rm -rf lasrc_toa
mkdir lasrc_toa && cd lasrc_toa

ln -s $input_dir/*.img .
ln -s $input_dir/*.hdr .
cp $input_dir/*.xml .
chmod u+w *.xml

# Run LASRC with SR and TOA outputs enabled
$bin_dir/lasrc --xml=${base_scene}.xml --aux=${aux_file} --num_threads 6 --write_toa
if [ $? -ne 0 ]; then
    echo "Error: lasrc processing failed."
    exit 1
fi

# Compare the results.
status=0
for i in "${data_files[@]}"; do
    base_name=`basename $i`

    echo "Comparing $base_name... "

    if [ ! -f $base_name ]; then
        echo "Warn ${base_name} does not exist."
        continue;
    fi

    # For the XML file, ignore the records that vary from one run to the next.
    # If the file is an ASCII header file, use diff.  Otherwise, assume it's
    # a binary file, and use cmp to dump the octal differences.
    ext="${i##*.}"
    if [ "$ext" = "xml" ]; then
        sed -e 's%<production_date>.*<%<production_date><%' $i > tmp1.xml
        sed -e 's%<production_date>.*<%<production_date><%' $base_name > \
                                                                      tmp2.xml
        diff tmp1.xml tmp2.xml
        if [ $? -ne 0 ]; then
            echo "${base_name} differs from reference version."
            status=1
        fi
    elif [ "$ext" = "hdr" ]; then
        diff $i $base_name
        if [ $? -ne 0 ]; then
            echo "${base_name} differs from reference version."
            status=1
        fi
    else
        lines=`grep lines ${i%.img}.hdr | awk '{print $3}'`
        samples=`grep samples ${i%.img}.hdr | awk '{print $3}'`
        dtype=`grep "data type" ${i%.img}.hdr | awk '{print $4}'`
        if [ "$dtype" = "1" ]; then
            depth=8
        else
            depth=16
        fi
        numdiffs=`compare -metric AE -depth $depth -size ${samples}x${lines} \
                      gray:$i gray:${base_name} null: 2>&1`
        if [ "x$numdiffs" != "x0" ]; then
            echo "${base_name} differs from reference version in $numdiffs " \
                 "pixels."
            status=1
        fi
    fi
done

if [ $status -ne 0 ]; then
    echo "Test differences found."
    exit 1
fi

cd ..
rm -rf lasrc_toa

echo "Test completed successfully."
exit 0
