#!/usr/bin/env bash

TIME_LIMIT=900 # time (in seconds) on a test after which the solver is killed
TIME_LIMIT_MS=$(($TIME_LIMIT * 1000))

# test generator parameters
RESULTS_FOLDER="tests/results"
REQUESTS_FOLDER="tests/requests"
NETWORKS=("maritimes" "quebecL3" "quebecL2")
NUM_REQUESTS_PER_FILE=50
NUM_EVS=(2 4 8 16 32 64 128 256 512 1024)

# solver parameters
SOLVERS=("nocoop" "coopStartFirst" "coopLogFact" "coopCascade")

function main {
  mkdir -p results
  mkdir -p requests
  cd ..

  # Clean and compile the planner
  make clean
  make

  generate_tests
  run_tests_and_save_results
  process_results

  cd - > /dev/null
}

function generate_tests {
  echo "-- generate_tests $1 --"
  for n in ${NETWORKS[*]}; do
    for nEVs in ${NUM_EVS[*]}; do
      echo -e "\tGenerating file for ${n}, NumRequests = ${NUM_REQUESTS_PER_FILE}, nEVs = ${nEVs}"
      ./veCoopV2 -f "tests/${n}.graphe" -g $NUM_REQUESTS_PER_FILE -n $nEVs -m 1 > "${REQUESTS_FOLDER}/${n}_${nEVs}.requests"
    done
  done
}

function run_tests_and_save_results {
  echo "-- run_tests_and_save_results --"
  declare -A stopdict=()
  for n in ${NETWORKS[*]}; do
    requests=( $(/bin/ls -1v ${REQUESTS_FOLDER}/${n}*.requests) )
    for r in ${NUM_EVS[*]}; do
      echo -e "\t${n} ${r}"
      for s in ${SOLVERS[*]}; do
        echo -e "\t\t${s}"
        OUTPUT_FILE="${RESULTS_FOLDER}/${n}_${r}_${s}.bench"
        REQUEST_FILE="${REQUESTS_FOLDER}/${n}_${r}.requests"
        if [[ ${stopdict["${n}_${s}"]} == true ]]; then
          solver_status=124
        else
          ulimit -m 25165824
          timeout $TIME_LIMIT \
            ./veCoopV2 -f "tests/${n}.graphe" -s "$s" -r "${REQUEST_FILE}" > $OUTPUT_FILE
          solver_status=$?
        fi

        if [[ $solver_status -gt 100 ]]; then # There was a timeout
          stopdict["${n}_${s}"]=true
        fi
      done

      # Concatenate info from all solvers in one file
      args=()
      for s in "${SOLVERS[@]}"; do
        args+=("${RESULTS_FOLDER}/${n}_${r}_${s}.bench")
      done
      paste "${args[@]}" > ${RESULTS_FOLDER}/${n}_${r}_total.bench
    done
  done
}

function process_results {
  echo "-- process_results --"
  args=()
  for n in ${NETWORKS[*]}; do
    args+=("${RESULTS_FOLDER}/${n}.table")
    results=( $(/bin/ls -1v ${RESULTS_FOLDER}/${n}_*_total.bench) )
    ./tests/process_results "${results[@]}" > ${RESULTS_FOLDER}/${n}.table
  done

  cat "${args[@]}" > ${RESULTS_FOLDER}/complete.table
  awk 'BEGIN { OFS = "\t" } { print $1, $2, $7, $8, $13, $14, $19, $20, $25, $26 }' ${RESULTS_FOLDER}/complete.table > ${RESULTS_FOLDER}/results.latex
}

main "$@"
