#!/usr/bin/env bash

set -euo pipefail

export AWS_LC_SYS_USE_SYSTEM=0
export AWS_LC_SYS_NO_JITTER_ENTROPY=1

MAX_PARALLEL_JOBS=24
RESULTS_DIR="/tmp/wtx-bench-results"

active_jobs=0
backends=("aws-lc-rs" "graviola" "openssl" "ring")
certificates=("ecdsasecp256r1sha256" "ecdsasecp384r1sha384" "ed25519" "rsapssrsaesha256" "rsapssrsaesha384")
cipher_suites=("aes128gcmsha256" "aes256gcmsha384" "chacha20poly1305sha256")
named_groups=("secp256r1" "secp384r1" "x25519")

rm -rf /tmp/wtx-bench-bins
rm -rf /tmp/wtx-bench-builds
rm -rf $RESULTS_DIR
mkdir -p /tmp/wtx-bench-bins
mkdir -p /tmp/wtx-bench-builds
mkdir -p "$RESULTS_DIR"

for cipher_suite in "${cipher_suites[@]}"; do
  for named_group in "${named_groups[@]}"; do
    for backend in "${backends[@]}"; do
      features="$backend $cipher_suite $named_group"
      id=$(echo "$features" | xargs | tr ' ' '_') 
      if [[ -f "/tmp/wtx-bench-bins/$id" ]]; then
        continue
      fi
      tmp_dir="/tmp/wtx-bench-builds/$id"
      (
        CARGO_TARGET_DIR="$tmp_dir" \
        cargo build --features "$features" --quiet --profile deploy
        mv "$tmp_dir/deploy/wtx-bench" "/tmp/wtx-bench-bins/$id"
        rm -rf "$tmp_dir"
      ) &
      active_jobs=$((active_jobs + 1))
      if [[ $active_jobs -ge $MAX_PARALLEL_JOBS ]]; then
        wait -n
        active_jobs=$((active_jobs - 1))
      fi
    done
  done
done

wait

for cipher_suite in "${cipher_suites[@]}"; do
  for named_group in "${named_groups[@]}"; do
    for backend in "${backends[@]}"; do
      features="$backend $cipher_suite $named_group"
      id=$(echo "$features" | xargs | tr ' ' '_') 
      for certificate in "${certificates[@]}"; do
        echo -e "\e[0;33m***** Running $certificate with features [$features] *****\e[0m"
        csv_output="${RESULTS_DIR}/${id}_${certificate}.csv"
        run_name="${backend},${cipher_suite},${named_group},${certificate}"
        CA="$(cat "assets/${certificate}_ca.pem")" \
        PK="$(cat "assets/${certificate}_pk.pem")" \
        SK="$(cat "assets/${certificate}_sk.pem")" \
        hyperfine -N --runs 10 --warmup 10 \
          --command-name "$run_name" \
          --export-csv "$csv_output" \
          "/tmp/wtx-bench-bins/$id"
        tail -n +2 "$csv_output" >> "$RESULTS_DIR/all_results.csv"
      done
    done
  done
done

cargo run --bin plotter --features plotters