#!/usr/bin/env bash
set -e
wai=$(dirname $(readlink -f "$0")) # Current script directory
zmq=${wai}/ina260-zmq-publisher
source ${wai}/config # Load experiment configuration
bbexec="ssh -q ${bbhost}"
nosync="no" # change this to yes ONLY FOR TESTS

# Ensure zmq publisher is available
[ ! -d "${zmq}" ] && git clone https://gitlab.com/manzerbredes/ina260-zmq-publisher.git "${zmq}"
# Configuring zmq project
echo "Configuring ina260-zmq-publisher"
sed "s/^SUBSCRIBER_ADDR=.*/SUBSCRIBER_ADDR=${hostip}/g" -i ${zmq}/config.mk
sed "s/^ZMQ_PORT=.*/ZMQ_PORT=${zmqport}/g" -i ${zmq}/config.mk
sed "s/^LOG_DELAY=.*/LOG_DELAY=${zmqlogdelay}/g" -i ${zmq}/config.mk
sed "s/^LOG_INTERVAL=.*/LOG_INTERVAL=${zmqloginterval}/g" -i ${zmq}/config.mk
sed "s/^ZMQ_MSG_SIZE=.*/ZMQ_MSG_SIZE=${zmqmsgsize}/g" -i ${zmq}/config.mk
sed "s/^MAX_QUEUE=.*/MAX_QUEUE=${zmqmaxqueue}/g" -i ${zmq}/config.mk

# Setting up beaglebone
[ ${nosync} != "yes" ] && rsync -avh --exclude=".git*" --exclude="ina260-zmq-publisher/data" ina260-zmq-publisher pure-read run_beaglebone.sh config ${bbhost}:sandbox/

# Cleaning previous results
[ -x "${zmq}/data" ] && rm -rf "${zmq}/data"

##### Run experiments
# Start zmq subscriber on the host
echo "Starting subscriber"
cd $zmq
make -B
make subscribe &
zmqpid=$!
cd - > /dev/null
# Start iperf
iperf -s -fm -o netstats.txt &
iperfpid=$!
# Start experiments
$bbexec "cd sandbox && ./run_beaglebone.sh"

# Collect pure-read results
echo "Fetching pure-read results"
rsync -avh ${bbhost}:sandbox/pure_read.csv ${wai}/../analysis/results/

# Collect zmq results
echo "Formatting zmq results"
. ${wai}/config
zmqcsv="${wai}/../analysis/results/zmq.csv"
echo "bus,addr,deviceid,usen,duration,loginterval,logdelay,rest,msgsize,timestamp,nsecs,power" > "$zmqcsv"
for exp in ${zmq}/data/*
do
    usen=$(basename $exp|sed "s/usen//g")
    for dev in $exp/*
    do
        deviceid=$(basename $dev)
        bus=$(echo $deviceid|cut -d\- -f1)
        addr=0x$(echo $deviceid|cut -d\- -f2|awk '{print $0+0}')
        infos="${bus},${addr},${bus}-${addr},${usen},${zmqduration},${zmqloginterval},${zmqlogdelay},${zmqrest},${zmqmsgsize}"
        cat $dev/* | awk '!/timestamp/{print("'$infos',"$0)}' >> "$zmqcsv"
    done
done

# Collecting iperf results
echo "Formatting iperf results"
bw=$(cat netstats.txt |awk -F '[ -]+' '/sec/{print $8}') # Mbps
iperfcsv="${wai}/../analysis/results/iperf.csv"
echo "bw" > "$iperfcsv"
echo "${bw}" >> "$iperfcsv"

# Stopping zmq subscriber and iperf
echo "Stopping subscriber..."
kill $zmqpid
echo "Stopping iperf..."
kill $iperfpid
echo "Finished congratulations!"
