#! /usr/bin/env bash
# Copyright (c) 2016 Michael David Adams
################################################################################

################################################################################

if [ "${BASH_VERSINFO[0]}" -lt 4 ]; then
	echo "This test requires Bash 4 or greater."
	echo "This test is being skipped."
	exit 0
fi

cmd_dir=$(dirname "$0") || exit 1
source "$cmd_dir"/utilities || exit 1

################################################################################

set_source_and_build_dirs || panic "cannot set source and build directories"

################################################################################

#abs_source_dir="$1"
#abs_build_dir="$2"

#export JAS_ABS_TOP_BUILDDIR="$abs_build_dir"
#export JAS_TOP_BUILDDIR="$abs_build_dir"
#export JAS_ABS_TOP_SRCDIR="$abs_source_dir"
#export JAS_TOP_SRCDIR="$abs_source_dir"

#$CMDDIR/rundectests jasper || exit 1

oj_compress=$(which opj2_compress) || oj_compress=""
oj_decompress=$(which opj2_decompress) || oj_decompress=""

run_test="$cmd_dir/run_codec_test"

codec_selectors=()
codec_selectors+=(jasper_jasper)
if [ -n "$oj_decompress" ]; then
	codec_selectors+=(jasper_oj)
fi
#codec_selectors+=(jasper_jj2k)
#codec_selectors+=(jj2k_jasper)
#codec_selectors+=(kakadu_jasper)
#codec_selectors+=(jasper_kakadu)
###codec_selectors+=(jasper_vm)
###codec_selectors+=(vm_jasper)

echo "STARTING AT `date`"

num_errors=0
failed_tests=()

for codec_selector in "${codec_selectors[@]}"; do
	enc=$(echo "$codec_selector" | awk -v FS=_ '{print $1}' -)
	dec=$(echo "$codec_selector" | awk -v FS=_ '{print $2}' -)
	echo "############################################################"
	echo "START OF TESTS FOR ENCODER=$enc DECODER=$dec"
	echo "############################################################"
	opts=()
	opts+=(-v)
	opts+=(-e "$enc")
	opts+=(-d "$dec")
	opts+=(-E ignore)
	#opts+=(-B)
	opts+=("$@")
	"$run_test" "${opts[@]}"
	status=$?
	if [ $status -ne 0 ]; then
		num_errors=$((num_errors + 1))
		failed_tests+=($codec_selector)
		#panic "running tests failed"
	fi
	echo "############################################################"
	echo "END OF TESTS"
	echo "############################################################"
done

echo "ENDING AT `date`"

echo "############################################################"
echo "TEST SUMMARY"
echo "Number of codec selectors: ${#codec_selectors[@]}"
echo "Number of errors: $num_errors"
if [ "$num_errors" -gt 0 ]; then
	echo "STATUS: FAILED"
	exit 1
fi
echo "STATUS: PASSED"
