#!/usr/bin/env bash
set -euo pipefail

cd /src

LOG_FILE="auto-tests.detail.log"
: > "$LOG_FILE"

mvn -q -DskipTests compile \
    dependency:build-classpath -Dmdep.outputFile=target/autotest.cp
runtime_cp="target/classes:$(cat target/autotest.cp)"

printf "%-40s | %-10s | %-10s | %-10s\n" \
  "TestClass" "Total" "Success" "Fail"
printf "%-40s-+-%-10s-+-%-10s-+-%-10s\n" \
"----------------------------------------" "----------" "----------" "----------"


overall_total=0
overall_fail=0

for class_file in $(find target/classes/com/kucoin/universal/sdk/generate \
                      -type f -name '*AutoGeneratedTest.class' | sort); do
  fqcn=${class_file#target/classes/}
  fqcn=${fqcn%.class}
  fqcn=${fqcn//\//.}
  simple=$(basename "$class_file" .class)

  out=$(java -cp "$runtime_cp" "$fqcn" 2>&1 | tee -a "$LOG_FILE" || true)
  summary=$(grep -E 'Test total:' <<< "$out" || true)

  if [[ -n $summary ]]; then
    total=$(grep -oE 'total:[[:space:]]*[0-9]+'  <<< "$summary" | grep -oE '[0-9]+')
    fail=$( grep -oE 'failed:[[:space:]]*[0-9]+' <<< "$summary" | grep -oE '[0-9]+')
    fail=${fail:-0}
  else
    total=0
    fail=0
  fi

  success=$((total - fail))
  printf "%-40s | %-10d | %-10d | %-10d\n" \
    "$simple" "$total" "$success" "$fail"

  overall_total=$((overall_total + total))
  overall_fail=$((overall_fail + fail))
done

overall_success=$((overall_total - overall_fail))

printf "%-40s-+-%-10s-+-%-10s-+-%-10s\n" \
  "----------------------------------------" "----------" "----------" "----------"
printf "%-40s | %-10d | %-10d | %-10d\n" \
  "Overall Summary" "$overall_total" "$overall_success" "$overall_fail"

exit "$overall_fail"
