#!/usr/bin/env bash

set -e

# verifies that RIFT environment is installed properly
# by running a mini topo checking for redis install
# and then some larger topology to check throughput.
# We switch off flood reduction to get really heavy load

ulimit -n 4096

echo "--- running small topology ..."

[ `../bin/rift-environ topology -DD ../topology/two.yaml | ./lib/countties.sh` -gt 0 ] || {
    echo "CRIT : rift over two nodes doesn't work, please check your installation ..."
    exit 1
}

[ redis-cli ] || {
    echo "WARN : most likely redis is not installed on local node, redis options will not work ..."
}

echo "OK   : all looks good for small topologies ..."

echo

OF=/tmp/rift.out.$$

echo "--- running larger topology into $OF ..."
echo

time ../bin/rift-environ -f topology -DD ../topology/3pod2edge4acc3core100pfx.yaml > $OF

[ -f $OF ] || { echo "CRIT: cannot run large topology"; exit 1; }

echo

./lib/eventstats.sh $OF

TT=`./lib/countfloodcountfilter.sh < $OF | cut -d: -f2`
TR=`./lib/countfloodretransmits.sh < $OF | cut -d: -f2`
TO=`./lib/countfloodreductions.sh < $OF | cut -d: -f2`

echo
echo "ties flood occurences on all links: " $TT
echo "ties retransmitted: " $TR
echo "ties flood suppressed: " $TO

TT=$(( $TT + 1 ))

PERCENT_RETRANSMIT=$(( 100 * $TR / $TT ))

echo TIE retransmission rate: $PERCENT_RETRANSMIT %% ...
echo

(( $PERCENT_RETRANSMIT > 5 )) && {
    echo "WARN : UDP has low throughput, your flooding doesn't work well, "
    echo "       disable VPN/firewalls/antivirus or tune UDP"
    echo "       you may also have too few cores to run larger topologies"
    echo
}

(( $PERCENT_RETRANSMIT > 15 )) && {
    echo "ERROR: UDP has very low throughput, your flooding doesn't work,"
    echo "       disable VPN/firewalls/antivirus or tune UDP"
    echo "       you may also have too few cores to run larger topologies"
    echo
}

C1P=`python lib/curlies.py "RIB stats for core_1" < $OF | python lib/curlies.py " *IPV4: AFRoutingTableStatistics" | egrep "currentprefixes" | cut -d: -f2 | cut -d, -f1`

(( $C1P < 600 )) && {
    echo "CRIT : Core 1 does not see all prefixes, only $C1P instead of 600, something is wrong, "
    echo "       most likely your flooding doesn't work properly, disable VPN/firewalls/antivirus,"
    echo "       tune UDP, check system configuration"
    echo
    exit 1
}

unlink $OF

echo OK   : all looks good for large topologies ...
