#!/bin/sh
# Run the unit program and the shell suites, side by side up to JOBS at a
# time (JOBS=1: one after another, the old behaviour), each to its own log in
# BUILD_DIR/logs. Then print the logs in a fixed order (unit, run.sh, store.sh,
# place.sh, project.sh, usage.sh, curate.sh, curate_apply.sh) and exit non-zero if any suite failed or printed no
# summary line.
# usage: suites.sh BUILD_DIR [SUITE...]   (BUILD_DIR holds suit and unit)
# SUITE is one of unit run store place project usage curate curate_apply; with none, all eight.
set -u
if [ "${1:-}" = --one ]; then
    # the worker: suites.sh --one BUILD_DIR NAME
    dir=$2 name=$3
    case $dir in /*) ;; *) dir=$PWD/$dir ;; esac
    start=$(date +%s)
    case $name in
        unit) "$dir/unit" ;;
        *) SUIT=$dir/suit sh "test/$name.sh" ;;
    esac >"$dir/logs/$name.log" 2>&1
    echo $? >"$dir/logs/$name.rc"
    echo $(($(date +%s) - start)) >"$dir/logs/$name.sec"
    exit 0
fi

dir=${1:?usage: suites.sh BUILD_DIR [SUITE...]}
shift
case $dir in /*) ;; *) dir=$PWD/$dir ;; esac
jobs=${JOBS:-1}
want=${*:-unit run store place project usage curate curate_apply}
rm -rf "$dir/logs"
mkdir -p "$dir/logs" build/tmp
trap 'exit 130' INT TERM

# longest first, so the slowest suite starts at once
order=
for n in store place project usage curate curate_apply run unit; do
    case " $want " in *" $n "*) order="$order $n" ;; esac
done

if [ "$jobs" -le 1 ]; then
    for n in $order; do sh "$0" --one "$dir" "$n"; done
else
    # shellcheck disable=SC2086
    printf '%s\n' $order | xargs -P "$jobs" -n 1 sh "$0" --one "$dir"
fi

status=0
times=
for n in unit run store place project usage curate curate_apply; do
    case " $want " in *" $n "*) ;; *) continue ;; esac
    cat "$dir/logs/$n.log"
    rc=$(cat "$dir/logs/$n.rc" 2>/dev/null || echo missing)
    times="$times $n $(cat "$dir/logs/$n.sec" 2>/dev/null || echo '?')s"
    if [ "$n" = unit ]; then pat='^unit: [0-9]* checks, [0-9]* failed$'
    else pat="^$n.sh: [0-9]* cases, [0-9]* failed\$"; fi
    if [ "$rc" != 0 ]; then
        echo "suites: $n exited $rc" >&2; status=1
    elif ! grep -q "$pat" "$dir/logs/$n.log"; then
        echo "suites: $n printed no summary line" >&2; status=1
    fi
done
echo "suites (JOBS=$jobs, seconds):$times"
exit $status
