#! /usr/bin/env bash
################################################################################

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

debug_level="${JAS_DEBUG_LEVEL:-0}"
if [ "$debug_level" -ge 1 ]; then
	set -xv
fi

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

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

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

top_dir="$cmd_dir/../.."

data_dir="$abs_top_srcdir/data"

test_program="$abs_top_builddir/src/app/multithread"
jasper_program="$abs_top_builddir/src/app/jasper"
#export IMGINFO_COMMAND="$imginfo"
export JASPER_COMMAND="$jasper_program"

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

verbose=0
if [ $# -ge 1 ]; then
	verbose=1
fi

tmp_dir=$(make_tmp_dir)

log_file=$tmp_dir/log

has_jpg_codec="$(is_supported_format jpg)" || \
  panic "cannot determine if JPG is supported format"
#"$jasper_program" --list-enabled-formats | grep -q jpg
#if [ $? -eq 0 ]; then
#	has_jpg_codec=1
#else
#	has_jpg_codec=0
#fi

echo "supports JPEG codec: $has_jpg_codec"

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

error_count=0

in_formats=()
in_formats+=(bmp)
if [ "$has_jpg_codec" -ne 0 ]; then
	in_formats+=(jpg)
fi
in_formats+=(pnm)
in_formats+=(ras)

out_formats=()
#in_formats+=(bmp)
out_formats+=(jp2)
#out_formats+=(pnm)
#in_formats+=(ras)

for out_format in "${out_formats[@]}"; do
	command=("$test_program")
	command+=(-f "$out_format")
	command+=(--job-debug-level 0)
	command+=(-r 1)
	command+=(--num-workers 4)
	command+=(--num-worker-iters 10000)
	command+=(--worker-debug-level 0)
	for in_format in "${in_formats[@]}"; do
		for file in "$data_dir"/images/*.$in_format; do
			if [ -e "$file" ]; then
				command+=("$file")
			fi
		done
	done
	if [ "$verbose" -gt 0 ]; then
		echo "RUNNING: ${command[@]}"
	fi
	"${command[@]}" >& ${log_file}
	status=$?
	if [ "$status" -ne 0 ]; then
		echo "============================================================"
		echo "COMMAND: ${command[@]}"
		cat "$log_file"
		echo "============================================================"
		error_count=$((error_count + 1))
	fi
done

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

echo "error count: $error_count"
if [ "$error_count" -gt 0 ]; then
	echo "STATUS: FAILED"
	panic "FAILED"
fi

echo "STATUS: PASSED"
