#!/bin/bash -e

executable="target/profiling/rawtojpg"
input_dir="${INPUT_DIR:-/mnt/sdcard/DCIM/101MSDCF}"
output_dir="${OUTPUT_DIR:-/home/cdown/testdir}"
runs=${RUNS:-50}
warmups=${WARMUPS:-5}

nice_cmd=(sudo nice -n -20 ionice -c 1 -n 0 sudo -u "${USER?}")
prepare_cmd="sh -c 'rm -rf $output_dir; mkdir $output_dir' && sudo sh -c 'sync && echo 3 > /proc/sys/vm/drop_caches'"

cargo build --profile profiling

if (( PROFILE )); then
    "${nice_cmd[@]}" samply record "$executable" "$input_dir" "$output_dir" "$@"
else
    "${nice_cmd[@]}" hyperfine --prepare "$prepare_cmd" --warmup "$warmups" --runs "$runs" -N "$executable $input_dir $output_dir $*"
fi

# Validate the files all look fine
in=( "$input_dir"/*.ARW )
out=( "$output_dir"/*.jpg )

if (( "${#in[@]}" == 0 )) || (( "${#in[@]}" != "${#out[@]}" )); then
    printf 'Wrong number of files: %d\n' "${#out[@]}" >&2
    exit 1
fi

if file "${out[@]}" | grep -vq 'JPEG image data'; then
    printf 'Bad image\n' >&2
    exit 1
fi