#!/bin/bash
# check-usability-of-sims
# HS-Fulda - sebastian.rieger@informatik.hs-fulda.de
#
# changelog:
# V1.0   initial version

# usage
if [ ! $# -gt 2 ] ; then
  echo -e "usage: $0 <username> <password> <timeout> [sim-regexp] [debug level], e.g.,\n"
  echo "$0 guest password 0.5"
  exit -1
fi

USERNAME=$1
PASSWORD=$2
TIMEOUT=$3
if [ $4 ]; then
  SIM_FILTER_REGEXP=$4
else
  SIM_FILTER_REGEXP="VIRLBENCH-(.*)@(.*)-[_a-zA-Z0-9]{6}"
fi
if [ $5 ]; then
  DEBUG=$5
else
  DEBUG=0
fi

# get all running benchmark simulations
SIMS=$(virl_std_client --username $USERNAME --password $PASSWORD --quiet --json simengine-list 2>&1 | egrep -o -e "$SIM_FILTER_REGEXP")
if [ $DEBUG -gt 1 ]; then
  echo "Running simulations:"
  for SIM in $SIMS; do
    echo $SIM
  done
  echo
fi

# Check if the nodes are ready-for-use using websocket consoles
TOTAL_USABLE_COUNT=0
TOTAL_AVG_DURATION=0
for SIM in $SIMS; do
  USABLE_COUNT=0
  AVG_DURATION=0
  WS_COUNT=$(virl_std_client --username $USERNAME --password $PASSWORD --quiet --json simengine-serial-port --session-id $SIM 2>&1 | grep -c "ws://")
  WS_NODES=$(virl_std_client --username $USERNAME --password $PASSWORD --quiet --json simengine-serial-port --session-id $SIM 2>&1 | grep "ws://")
  while [ $USABLE_COUNT -lt $WS_COUNT ]
  do
    USABLE_COUNT=0
    AVG_DURATION=0
    IFS=$'\n'
    for WS_NODE in $WS_NODES; do
      NODE=$(echo $WS_NODE | cut -d "\"" -f 2)
      WS_URL=$(echo $WS_NODE | cut -d "\"" -f 4)
      WS_RESULT=$(./check-reachability-websocket.py $WS_URL $NODE $TIMEOUT $DEBUG)
      if [ $? -eq 0 ]; then
        if [ $DEBUG -gt 0 ] ; then echo "$WS_RESULT: $NODE in $SIM is usable"; fi
        DURATION=$(echo $WS_RESULT | egrep -o -e '[0-9]\.[0-9]{6} \*sec elapsed\*' | cut -d ' ' -f 1)
        AVG_DURATION=$(awk "BEGIN {print $AVG_DURATION + $DURATION}")
        USABLE_COUNT=$(expr $USABLE_COUNT + 1)
      else
        if [ $DEBUG -gt 0 ] ; then echo "$WS_RESULT: $NODE in $SIM is unusable"; fi
      fi
    done
  done
  # compute average in millisecs
  TOTAL_AVG_DURATION=$(awk "BEGIN {print $TOTAL_AVG_DURATION + $AVG_DURATION}")
  TOTAL_USABLE_COUNT=$(expr $TOTAL_USABLE_COUNT + $USABLE_COUNT)
  AVG_DURATION=$(awk "BEGIN {print $AVG_DURATION / $USABLE_COUNT * 1000}")
  if [ $DEBUG -gt 0 ] ; then echo "$USABLE_COUNT of $WS_COUNT nodes in $SIM are usable... (avg console delay $AVG_DURATION ms)"; fi
done
# compute average in millisecs
TOTAL_AVG_DURATION=$(awk "BEGIN {print $TOTAL_AVG_DURATION / $TOTAL_USABLE_COUNT * 1000}")
if [ $DEBUG -gt 0 ] ; then echo "$TOTAL_USABLE_COUNT nodes usable total in all sims... (total avg console delay $TOTAL_AVG_DURATION ms)"; fi
echo "avgconsoledelay:$TOTAL_AVG_DURATION"