#!/usr/bin/env bash
# Runs the build and tests of each build folder a slice gate needs, and keeps their results for
# collect_tests.py (ADR-HIS-089).
#
#   HIS_SESSION=<gate session> run_tests.sh <results dir> <folder>...
#
# Java units run what the pipeline's build-test runs (platform/delivery-pipeline/bin/build-test):
# ./gradlew build on the light profile, then the policy check of a platform unit, with cleanTest and
# --no-build-cache so every test executes in this run, and --continue so a failing module does not
# keep the others from running. Script units go through build-test itself.
# Web packages run pnpm install, build and Vitest with a JUnit reporter as well. Each folder's results go to <results dir>/<folder with "/" as "__">/.
set -uo pipefail
results="$1"; shift
repo="$(cd "$(dirname "$0")/../../../../.." && pwd)"
mkdir -p "$results"
for folder in "$@"; do
  out="$results/${folder//\//__}"
  rm -rf "$out"; mkdir -p "$out"
  echo "== $folder" >&2
  kind="$(python3 -c 'import sys; sys.path.insert(0, sys.argv[1]); import plan; print(plan.kind(".", sys.argv[2]))' \
    "$repo/platform/delivery-pipeline/lib" "$folder" 2>/dev/null || echo unknown)"
  (cd "$repo"
   if [[ "$kind" == node ]]; then
     cd "$folder" && corepack enable >/dev/null 2>&1; pnpm install --frozen-lockfile && pnpm build \
       && pnpm exec vitest run --reporter=default --reporter=junit --outputFile.junit="$out/junit.xml"
   elif [[ "$kind" == java ]]; then
     # As build-test, but every test executes in this run: no result is taken from the build cache
     # or left up to date from an earlier run, so the record is the gate's own execution.
     platform/dev-environment/his-env start light \
       && (cd "$folder" && ./gradlew cleanTest build --continue --no-build-cache --no-daemon --stacktrace) \
       && { [[ "$folder" != platform/* ]] || platform/delivery-pipeline/bin/iac-policy "$folder"; }
   else
     platform/delivery-pipeline/bin/build-test "$folder"
   fi) > "$out/log.txt" 2>&1
  echo "$?" > "$out/status.txt"
  find "$repo/$folder" -path '*/node_modules' -prune -o -path '*/build/test-results/*' -name 'TEST-*.xml' -print 2>/dev/null | while read -r x; do
    rel="${x#"$repo/$folder/"}"; mkdir -p "$out/junit/$(dirname "$rel")"; cp "$x" "$out/junit/$rel"
  done
  [[ -f "$repo/$folder/test/out/results.json" ]] && cp "$repo/$folder/test/out/results.json" "$out/results.json"
  echo "   exit $(cat "$out/status.txt")" >&2
done
