#!/bin/bash
# Call: sh performance-test.sh
# Call: sh performance-test.sh E2E auto auto SYNC REEL
# Call: sh performance-test.sh 1 orgX perf ASYNC FIXE

SCENARIO=${1:-E2E}
ORGANISATION=${2:-auto}
LOT_PREFIX=${3:-auto}
MODE=${4:-SYNC}
DUREE_USAGE=${5:-FIXE}

. ./.env

# CONSTANTS
ARR_DATASET=(${E2E// /,} ${XS// /,} ${S// /,} ${M// /,} ${L// /,} ${XL// /,})
ARR_MAPPING=(E2E XS S M L XL)

if [ "${ORGANISATION}" = "auto" ];then ORGANISATION=org;fi
if [ "${LOT_PREFIX}" = "auto" ];then LOT_PREFIX=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 5);fi

if [ -d reports ]; then rm -rf reports; fi
mkdir reports
echo ${HEADER_RESULT} >reports/result.csv
echo ${HEADER_DETAIL} >reports/detail.csv

cfg_scenario="SCENARIO_${SCENARIO}"
echo "Config scenario: $cfg_scenario = ${!cfg_scenario}"
i=0
for nbIt in ${!cfg_scenario}; do
    dataset=${ARR_MAPPING[$i]}
    dataset_detail=${ARR_DATASET[$i]}
    i=$((i + 1))
    if [ "${nbIt}" = "0" ]; then continue; fi
    dataset_size_mb=0
    dataset_size_line=0
    ### Generate dataset ###
    echo "launch dataset ($dataset), detail : $dataset_detail"
    sh 2_generate_dataset.sh ${dataset_detail//,/ }
    dataset_size_mb=$(cat data/sizes.csv | grep TOTAL | cut -d',' -f2)
    dataset_size_line=$(cat data/sizes.csv | grep TOTAL | cut -d',' -f3)
    mv data/sizes.csv reports/sizes_${dataset}.csv
    start=$(date +%s)
    for ((j = 1; j <= $nbIt; j++)); do
        ### For each iteration load input, submit calculations and check ###
        echo "*** Organisation: $ORGANISATION, NomLot: ${LOT_PREFIX}_${dataset}_${j} ***"
        sh 3_load_input.sh $ORGANISATION ${LOT_PREFIX}_${dataset}_${j} $SCENARIO $MODE $DUREE_USAGE
        start_it=$(date +%s)
        sh 4_check.sh $ORGANISATION ${LOT_PREFIX}_${dataset}_${j}
        end_it=$(date +%s)
        elapsed_it_sec=$(($end_it - $start_it))
        mv progress.log reports/${LOT_PREFIX}_${dataset}_${j}.log
        echo "$dataset,$j,$elapsed_it_sec" >>reports/detail.csv
    done
    end=$(date +%s)
    elapsed_sec=$(($end - $start))
    echo "$dataset,$dataset_size_mb,$dataset_size_line,$nbIt,$(($elapsed_sec / $nbIt)),$elapsed_sec" >>reports/result.csv
done

cat reports/result.csv

if [ "${SCENARIO}" = "E2E" ]; then
    sh 5_assert.sh $ORGANISATION ${LOT_PREFIX}_E2E_1
fi
