#!/usr/bin/env bash

set -e

wai=$(dirname $(readlink -f "$0"))
scenarios="${wai}/../scenarios"
inputs="${wai}/../inputs.json"
simulator="make -C ${wai}/../ run"
sched="${wai}/scheduler/analysis.sh"
parser="${wai}/../parser.awk"
results="${wai}/results.csv"
aheaders="simkey,wireless,wakeupfor"
avalues="none,none,none"
log_file="${wai}/logs/$(date +%s).org" && mkdir -p "${wai}/logs/"
gen_log=0 # Should we generate logs ?

run-simulation () {
    # Generate inputs
    $scenarios $seed $simtime $wakeupevery $wakeupfor $n_nodes $extended $hint $poff $pon $prx $ptx $datasize $bitrate $hintsize $latency > "$inputs"
    
    # Init logs
    [ $gen_log -eq 1 ] && echo -e "* seed=$seed simtime=$simtime wakeupevery=$wakeupevery wakeupfor=$wakeupfor n_nodes=$n_nodes extended=$extended hint=$hint poff=$poff pon=$pon prx=$prx ptx=$ptx datasize=$datasize bitrate=$bitrate \n" >> "${log_file}"

    # Run simulations
    tmp=$(mktemp)
    $simulator &> $tmp
    [ $gen_log -eq 1 ] && cp $tmp "${log_file}"

    # Gen csv
    [ ! -e "$results" ] && { cat $tmp | $parser | sed "1 s/$/,${aheaders}/g" | sed "2,\$s/$/,${avalues}/" > "$results"; }
    [ -e "$results"  ] && { cat $tmp | $parser | sed 1d | sed "s/$/,${avalues}/" >> "$results"; }

    # Gen scheduler analysis
    #[ $seed -eq 1 ] && $sched $tmp "logs/$(echo ${avalues}|tr ',' '_')_hint${hint}_extended${extended}.png"

    # Clear tmp
    cat $tmp
    rm $tmp
}

# Default Parameters
seed=0
simtime=86400 # One day
wakeupevery=3600
wakeupfor=60
n_nodes=13
extended="false"
hint="false"
poff=0
pon=0.4
prx=0.16
ptx=0.16
datasize=1000000 # 1Mb
hintsize=8 # Integer
latency=0 # in Seconds
bitrate="100kbps"



run-scenarios() {
    # Configure number of seed per scenarios
    nseed=200

    # Baseline
    avalues="baseline,$wireless,$wakeupfor"
    for seed in 17
    do
        printf "\rBaseline...${seed}"
        run-simulation
    done
    echo 
}

# Clean previous runs
[ -e "${results}" ] && rm "${results}"

for wakeupfor in 60
do

    # Lora
    echo "----- Run Lora (wakeupfor=$wakeupfor) -----"
    wireless="lora"
    bitrate="50kbps"
    pon=0.4
    prx=0.16
    ptx=0.16
    latency=0
    run-scenarios
done